1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""BzrDir logic. The BzrDir is the basic control directory used by bzr.
19
At format 7 this was split out into Branch, Repository and Checkout control
22
Note: This module has a lot of ``open`` functions/methods that return
23
references to in-memory objects. As a rule, there are no matching ``close``
24
methods. To free any associated resources, simply stop referencing the
28
# TODO: Move old formats into a plugin to make this file smaller.
33
from bzrlib.lazy_import import lazy_import
34
lazy_import(globals(), """
35
from stat import S_ISDIR
47
revision as _mod_revision,
57
from bzrlib.osutils import (
60
from bzrlib.smart.client import _SmartClient
61
from bzrlib.store.versioned import WeaveStore
62
from bzrlib.transactions import WriteTransaction
63
from bzrlib.transport import (
64
do_catching_redirections,
67
remote as remote_transport,
69
from bzrlib.weave import Weave
72
from bzrlib.trace import (
84
"""A .bzr control diretory.
86
BzrDir instances let you create or open any of the things that can be
87
found within .bzr - checkouts, branches and repositories.
90
the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
92
a transport connected to the directory this bzr was opened from
93
(i.e. the parent directory holding the .bzr directory).
95
Everything in the bzrdir should have the same file permissions.
99
"""Invoke break_lock on the first object in the bzrdir.
101
If there is a tree, the tree is opened and break_lock() called.
102
Otherwise, branch is tried, and finally repository.
104
# XXX: This seems more like a UI function than something that really
105
# belongs in this class.
107
thing_to_unlock = self.open_workingtree()
108
except (errors.NotLocalUrl, errors.NoWorkingTree):
110
thing_to_unlock = self.open_branch()
111
except errors.NotBranchError:
113
thing_to_unlock = self.open_repository()
114
except errors.NoRepositoryPresent:
116
thing_to_unlock.break_lock()
118
def can_convert_format(self):
119
"""Return true if this bzrdir is one whose format we can convert from."""
122
def check_conversion_target(self, target_format):
123
target_repo_format = target_format.repository_format
124
source_repo_format = self._format.repository_format
125
source_repo_format.check_conversion_target(target_repo_format)
128
def _check_supported(format, allow_unsupported,
129
recommend_upgrade=True,
131
"""Give an error or warning on old formats.
133
:param format: may be any kind of format - workingtree, branch,
136
:param allow_unsupported: If true, allow opening
137
formats that are strongly deprecated, and which may
138
have limited functionality.
140
:param recommend_upgrade: If true (default), warn
141
the user through the ui object that they may wish
142
to upgrade the object.
144
# TODO: perhaps move this into a base Format class; it's not BzrDir
145
# specific. mbp 20070323
146
if not allow_unsupported and not format.is_supported():
147
# see open_downlevel to open legacy branches.
148
raise errors.UnsupportedFormatError(format=format)
149
if recommend_upgrade \
150
and getattr(format, 'upgrade_recommended', False):
151
ui.ui_factory.recommend_upgrade(
152
format.get_format_description(),
155
def clone(self, url, revision_id=None, force_new_repo=False,
156
preserve_stacking=False):
157
"""Clone this bzrdir and its contents to url verbatim.
159
:param url: The url create the clone at. If url's last component does
160
not exist, it will be created.
161
:param revision_id: The tip revision-id to use for any branch or
162
working tree. If not None, then the clone operation may tune
163
itself to download less data.
164
:param force_new_repo: Do not use a shared repository for the target
165
even if one is available.
166
:param preserve_stacking: When cloning a stacked branch, stack the
167
new branch on top of the other branch's stacked-on branch.
169
return self.clone_on_transport(get_transport(url),
170
revision_id=revision_id,
171
force_new_repo=force_new_repo,
172
preserve_stacking=preserve_stacking)
174
def clone_on_transport(self, transport, revision_id=None,
175
force_new_repo=False, preserve_stacking=False,
177
"""Clone this bzrdir and its contents to transport verbatim.
179
:param transport: The transport for the location to produce the clone
180
at. If the target directory does not exist, it will be created.
181
:param revision_id: The tip revision-id to use for any branch or
182
working tree. If not None, then the clone operation may tune
183
itself to download less data.
184
:param force_new_repo: Do not use a shared repository for the target,
185
even if one is available.
186
:param preserve_stacking: When cloning a stacked branch, stack the
187
new branch on top of the other branch's stacked-on branch.
189
transport.ensure_base()
190
require_stacking = (stacked_on is not None)
191
format = self.cloning_metadir(require_stacking)
192
result = format.initialize_on_transport(transport)
193
repository_policy = None
195
local_repo = self.find_repository()
196
except errors.NoRepositoryPresent:
199
local_branch = self.open_branch()
200
except errors.NotBranchError:
203
# enable fallbacks when branch is not a branch reference
204
if local_branch.repository.has_same_location(local_repo):
205
local_repo = local_branch.repository
206
if preserve_stacking:
208
stacked_on = local_branch.get_stacked_on_url()
209
except (errors.UnstackableBranchFormat,
210
errors.UnstackableRepositoryFormat,
215
# may need to copy content in
216
repository_policy = result.determine_repository_policy(
217
force_new_repo, stacked_on, self.root_transport.base,
218
require_stacking=require_stacking)
219
make_working_trees = local_repo.make_working_trees()
220
result_repo = repository_policy.acquire_repository(
221
make_working_trees, local_repo.is_shared())
222
if not require_stacking and repository_policy._require_stacking:
223
require_stacking = True
224
result._format.require_stacking()
225
result_repo.fetch(local_repo, revision_id=revision_id)
228
# 1 if there is a branch present
229
# make sure its content is available in the target repository
231
if local_branch is not None:
232
result_branch = local_branch.clone(result, revision_id=revision_id,
233
repository_policy=repository_policy)
235
# Cheaper to check if the target is not local, than to try making
237
result.root_transport.local_abspath('.')
238
if result_repo is None or result_repo.make_working_trees():
239
self.open_workingtree().clone(result)
240
except (errors.NoWorkingTree, errors.NotLocalUrl):
244
# TODO: This should be given a Transport, and should chdir up; otherwise
245
# this will open a new connection.
246
def _make_tail(self, url):
247
t = get_transport(url)
251
def create(cls, base, format=None, possible_transports=None):
252
"""Create a new BzrDir at the url 'base'.
254
:param format: If supplied, the format of branch to create. If not
255
supplied, the default is used.
256
:param possible_transports: If supplied, a list of transports that
257
can be reused to share a remote connection.
259
if cls is not BzrDir:
260
raise AssertionError("BzrDir.create always creates the default"
261
" format, not one of %r" % cls)
262
t = get_transport(base, possible_transports)
265
format = BzrDirFormat.get_default_format()
266
return format.initialize_on_transport(t)
269
def find_bzrdirs(transport, evaluate=None, list_current=None):
270
"""Find bzrdirs recursively from current location.
272
This is intended primarily as a building block for more sophisticated
273
functionality, like finding trees under a directory, or finding
274
branches that use a given repository.
275
:param evaluate: An optional callable that yields recurse, value,
276
where recurse controls whether this bzrdir is recursed into
277
and value is the value to yield. By default, all bzrdirs
278
are recursed into, and the return value is the bzrdir.
279
:param list_current: if supplied, use this function to list the current
280
directory, instead of Transport.list_dir
281
:return: a generator of found bzrdirs, or whatever evaluate returns.
283
if list_current is None:
284
def list_current(transport):
285
return transport.list_dir('')
287
def evaluate(bzrdir):
290
pending = [transport]
291
while len(pending) > 0:
292
current_transport = pending.pop()
295
bzrdir = BzrDir.open_from_transport(current_transport)
296
except errors.NotBranchError:
299
recurse, value = evaluate(bzrdir)
302
subdirs = list_current(current_transport)
303
except errors.NoSuchFile:
306
for subdir in sorted(subdirs, reverse=True):
307
pending.append(current_transport.clone(subdir))
310
def find_branches(transport):
311
"""Find all branches under a transport.
313
This will find all branches below the transport, including branches
314
inside other branches. Where possible, it will use
315
Repository.find_branches.
317
To list all the branches that use a particular Repository, see
318
Repository.find_branches
320
def evaluate(bzrdir):
322
repository = bzrdir.open_repository()
323
except errors.NoRepositoryPresent:
326
return False, (None, repository)
328
branch = bzrdir.open_branch()
329
except errors.NotBranchError:
330
return True, (None, None)
332
return True, (branch, None)
334
for branch, repo in BzrDir.find_bzrdirs(transport, evaluate=evaluate):
336
branches.extend(repo.find_branches())
337
if branch is not None:
338
branches.append(branch)
341
def destroy_repository(self):
342
"""Destroy the repository in this BzrDir"""
343
raise NotImplementedError(self.destroy_repository)
345
def create_branch(self):
346
"""Create a branch in this BzrDir.
348
The bzrdir's format will control what branch format is created.
349
For more control see BranchFormatXX.create(a_bzrdir).
351
raise NotImplementedError(self.create_branch)
353
def destroy_branch(self):
354
"""Destroy the branch in this BzrDir"""
355
raise NotImplementedError(self.destroy_branch)
358
def create_branch_and_repo(base, force_new_repo=False, format=None):
359
"""Create a new BzrDir, Branch and Repository at the url 'base'.
361
This will use the current default BzrDirFormat unless one is
362
specified, and use whatever
363
repository format that that uses via bzrdir.create_branch and
364
create_repository. If a shared repository is available that is used
367
The created Branch object is returned.
369
:param base: The URL to create the branch at.
370
:param force_new_repo: If True a new repository is always created.
371
:param format: If supplied, the format of branch to create. If not
372
supplied, the default is used.
374
bzrdir = BzrDir.create(base, format)
375
bzrdir._find_or_create_repository(force_new_repo)
376
return bzrdir.create_branch()
378
def determine_repository_policy(self, force_new_repo=False, stack_on=None,
379
stack_on_pwd=None, require_stacking=False):
380
"""Return an object representing a policy to use.
382
This controls whether a new repository is created, or a shared
383
repository used instead.
385
If stack_on is supplied, will not seek a containing shared repo.
387
:param force_new_repo: If True, require a new repository to be created.
388
:param stack_on: If supplied, the location to stack on. If not
389
supplied, a default_stack_on location may be used.
390
:param stack_on_pwd: If stack_on is relative, the location it is
393
def repository_policy(found_bzrdir):
396
config = found_bzrdir.get_config()
398
if config is not None:
399
stack_on = config.get_default_stack_on()
400
if stack_on is not None:
401
stack_on_pwd = found_bzrdir.root_transport.base
403
note('Using default stacking branch %s at %s', stack_on,
405
# does it have a repository ?
407
repository = found_bzrdir.open_repository()
408
except errors.NoRepositoryPresent:
411
if ((found_bzrdir.root_transport.base !=
412
self.root_transport.base) and not repository.is_shared()):
419
return UseExistingRepository(repository, stack_on,
420
stack_on_pwd, require_stacking=require_stacking), True
422
return CreateRepository(self, stack_on, stack_on_pwd,
423
require_stacking=require_stacking), True
425
if not force_new_repo:
427
policy = self._find_containing(repository_policy)
428
if policy is not None:
432
return UseExistingRepository(self.open_repository(),
433
stack_on, stack_on_pwd,
434
require_stacking=require_stacking)
435
except errors.NoRepositoryPresent:
437
return CreateRepository(self, stack_on, stack_on_pwd,
438
require_stacking=require_stacking)
440
def _find_or_create_repository(self, force_new_repo):
441
"""Create a new repository if needed, returning the repository."""
442
policy = self.determine_repository_policy(force_new_repo)
443
return policy.acquire_repository()
446
def create_branch_convenience(base, force_new_repo=False,
447
force_new_tree=None, format=None,
448
possible_transports=None):
449
"""Create a new BzrDir, Branch and Repository at the url 'base'.
451
This is a convenience function - it will use an existing repository
452
if possible, can be told explicitly whether to create a working tree or
455
This will use the current default BzrDirFormat unless one is
456
specified, and use whatever
457
repository format that that uses via bzrdir.create_branch and
458
create_repository. If a shared repository is available that is used
459
preferentially. Whatever repository is used, its tree creation policy
462
The created Branch object is returned.
463
If a working tree cannot be made due to base not being a file:// url,
464
no error is raised unless force_new_tree is True, in which case no
465
data is created on disk and NotLocalUrl is raised.
467
:param base: The URL to create the branch at.
468
:param force_new_repo: If True a new repository is always created.
469
:param force_new_tree: If True or False force creation of a tree or
470
prevent such creation respectively.
471
:param format: Override for the bzrdir format to create.
472
:param possible_transports: An optional reusable transports list.
475
# check for non local urls
476
t = get_transport(base, possible_transports)
477
if not isinstance(t, local.LocalTransport):
478
raise errors.NotLocalUrl(base)
479
bzrdir = BzrDir.create(base, format, possible_transports)
480
repo = bzrdir._find_or_create_repository(force_new_repo)
481
result = bzrdir.create_branch()
482
if force_new_tree or (repo.make_working_trees() and
483
force_new_tree is None):
485
bzrdir.create_workingtree()
486
except errors.NotLocalUrl:
491
def create_standalone_workingtree(base, format=None):
492
"""Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
494
'base' must be a local path or a file:// url.
496
This will use the current default BzrDirFormat unless one is
497
specified, and use whatever
498
repository format that that uses for bzrdirformat.create_workingtree,
499
create_branch and create_repository.
501
:param format: Override for the bzrdir format to create.
502
:return: The WorkingTree object.
504
t = get_transport(base)
505
if not isinstance(t, local.LocalTransport):
506
raise errors.NotLocalUrl(base)
507
bzrdir = BzrDir.create_branch_and_repo(base,
509
format=format).bzrdir
510
return bzrdir.create_workingtree()
512
def create_workingtree(self, revision_id=None, from_branch=None,
513
accelerator_tree=None, hardlink=False):
514
"""Create a working tree at this BzrDir.
516
:param revision_id: create it as of this revision id.
517
:param from_branch: override bzrdir branch (for lightweight checkouts)
518
:param accelerator_tree: A tree which can be used for retrieving file
519
contents more quickly than the revision tree, i.e. a workingtree.
520
The revision tree will be used for cases where accelerator_tree's
521
content is different.
523
raise NotImplementedError(self.create_workingtree)
525
def backup_bzrdir(self):
526
"""Backup this bzr control directory.
528
:return: Tuple with old path name and new path name
530
pb = ui.ui_factory.nested_progress_bar()
532
# FIXME: bug 300001 -- the backup fails if the backup directory
533
# already exists, but it should instead either remove it or make
534
# a new backup directory.
536
# FIXME: bug 262450 -- the backup directory should have the same
537
# permissions as the .bzr directory (probably a bug in copy_tree)
538
old_path = self.root_transport.abspath('.bzr')
539
new_path = self.root_transport.abspath('backup.bzr')
540
pb.note('making backup of %s' % (old_path,))
541
pb.note(' to %s' % (new_path,))
542
self.root_transport.copy_tree('.bzr', 'backup.bzr')
543
return (old_path, new_path)
547
def retire_bzrdir(self, limit=10000):
548
"""Permanently disable the bzrdir.
550
This is done by renaming it to give the user some ability to recover
551
if there was a problem.
553
This will have horrible consequences if anyone has anything locked or
555
:param limit: number of times to retry
560
to_path = '.bzr.retired.%d' % i
561
self.root_transport.rename('.bzr', to_path)
562
note("renamed %s to %s"
563
% (self.root_transport.abspath('.bzr'), to_path))
565
except (errors.TransportError, IOError, errors.PathError):
572
def destroy_workingtree(self):
573
"""Destroy the working tree at this BzrDir.
575
Formats that do not support this may raise UnsupportedOperation.
577
raise NotImplementedError(self.destroy_workingtree)
579
def destroy_workingtree_metadata(self):
580
"""Destroy the control files for the working tree at this BzrDir.
582
The contents of working tree files are not affected.
583
Formats that do not support this may raise UnsupportedOperation.
585
raise NotImplementedError(self.destroy_workingtree_metadata)
587
def _find_containing(self, evaluate):
588
"""Find something in a containing control directory.
590
This method will scan containing control dirs, until it finds what
591
it is looking for, decides that it will never find it, or runs out
592
of containing control directories to check.
594
It is used to implement find_repository and
595
determine_repository_policy.
597
:param evaluate: A function returning (value, stop). If stop is True,
598
the value will be returned.
602
result, stop = evaluate(found_bzrdir)
605
next_transport = found_bzrdir.root_transport.clone('..')
606
if (found_bzrdir.root_transport.base == next_transport.base):
607
# top of the file system
609
# find the next containing bzrdir
611
found_bzrdir = BzrDir.open_containing_from_transport(
613
except errors.NotBranchError:
616
def find_repository(self):
617
"""Find the repository that should be used.
619
This does not require a branch as we use it to find the repo for
620
new branches as well as to hook existing branches up to their
623
def usable_repository(found_bzrdir):
624
# does it have a repository ?
626
repository = found_bzrdir.open_repository()
627
except errors.NoRepositoryPresent:
629
if found_bzrdir.root_transport.base == self.root_transport.base:
630
return repository, True
631
elif repository.is_shared():
632
return repository, True
636
found_repo = self._find_containing(usable_repository)
637
if found_repo is None:
638
raise errors.NoRepositoryPresent(self)
641
def get_branch_reference(self):
642
"""Return the referenced URL for the branch in this bzrdir.
644
:raises NotBranchError: If there is no Branch.
645
:return: The URL the branch in this bzrdir references if it is a
646
reference branch, or None for regular branches.
650
def get_branch_transport(self, branch_format):
651
"""Get the transport for use by branch format in this BzrDir.
653
Note that bzr dirs that do not support format strings will raise
654
IncompatibleFormat if the branch format they are given has
655
a format string, and vice versa.
657
If branch_format is None, the transport is returned with no
658
checking. If it is not None, then the returned transport is
659
guaranteed to point to an existing directory ready for use.
661
raise NotImplementedError(self.get_branch_transport)
663
def _find_creation_modes(self):
664
"""Determine the appropriate modes for files and directories.
666
They're always set to be consistent with the base directory,
667
assuming that this transport allows setting modes.
669
# TODO: Do we need or want an option (maybe a config setting) to turn
670
# this off or override it for particular locations? -- mbp 20080512
671
if self._mode_check_done:
673
self._mode_check_done = True
675
st = self.transport.stat('.')
676
except errors.TransportNotPossible:
677
self._dir_mode = None
678
self._file_mode = None
680
# Check the directory mode, but also make sure the created
681
# directories and files are read-write for this user. This is
682
# mostly a workaround for filesystems which lie about being able to
683
# write to a directory (cygwin & win32)
684
if (st.st_mode & 07777 == 00000):
685
# FTP allows stat but does not return dir/file modes
686
self._dir_mode = None
687
self._file_mode = None
689
self._dir_mode = (st.st_mode & 07777) | 00700
690
# Remove the sticky and execute bits for files
691
self._file_mode = self._dir_mode & ~07111
693
def _get_file_mode(self):
694
"""Return Unix mode for newly created files, or None.
696
if not self._mode_check_done:
697
self._find_creation_modes()
698
return self._file_mode
700
def _get_dir_mode(self):
701
"""Return Unix mode for newly created directories, or None.
703
if not self._mode_check_done:
704
self._find_creation_modes()
705
return self._dir_mode
707
def get_repository_transport(self, repository_format):
708
"""Get the transport for use by repository format in this BzrDir.
710
Note that bzr dirs that do not support format strings will raise
711
IncompatibleFormat if the repository format they are given has
712
a format string, and vice versa.
714
If repository_format is None, the transport is returned with no
715
checking. If it is not None, then the returned transport is
716
guaranteed to point to an existing directory ready for use.
718
raise NotImplementedError(self.get_repository_transport)
720
def get_workingtree_transport(self, tree_format):
721
"""Get the transport for use by workingtree format in this BzrDir.
723
Note that bzr dirs that do not support format strings will raise
724
IncompatibleFormat if the workingtree format they are given has a
725
format string, and vice versa.
727
If workingtree_format is None, the transport is returned with no
728
checking. If it is not None, then the returned transport is
729
guaranteed to point to an existing directory ready for use.
731
raise NotImplementedError(self.get_workingtree_transport)
733
def get_config(self):
734
if getattr(self, '_get_config', None) is None:
736
return self._get_config()
738
def __init__(self, _transport, _format):
739
"""Initialize a Bzr control dir object.
741
Only really common logic should reside here, concrete classes should be
742
made with varying behaviours.
744
:param _format: the format that is creating this BzrDir instance.
745
:param _transport: the transport this dir is based at.
747
self._format = _format
748
self.transport = _transport.clone('.bzr')
749
self.root_transport = _transport
750
self._mode_check_done = False
752
def is_control_filename(self, filename):
753
"""True if filename is the name of a path which is reserved for bzrdir's.
755
:param filename: A filename within the root transport of this bzrdir.
757
This is true IF and ONLY IF the filename is part of the namespace reserved
758
for bzr control dirs. Currently this is the '.bzr' directory in the root
759
of the root_transport. it is expected that plugins will need to extend
760
this in the future - for instance to make bzr talk with svn working
763
# this might be better on the BzrDirFormat class because it refers to
764
# all the possible bzrdir disk formats.
765
# This method is tested via the workingtree is_control_filename tests-
766
# it was extracted from WorkingTree.is_control_filename. If the method's
767
# contract is extended beyond the current trivial implementation, please
768
# add new tests for it to the appropriate place.
769
return filename == '.bzr' or filename.startswith('.bzr/')
771
def needs_format_conversion(self, format=None):
772
"""Return true if this bzrdir needs convert_format run on it.
774
For instance, if the repository format is out of date but the
775
branch and working tree are not, this should return True.
777
:param format: Optional parameter indicating a specific desired
778
format we plan to arrive at.
780
raise NotImplementedError(self.needs_format_conversion)
783
def open_unsupported(base):
784
"""Open a branch which is not supported."""
785
return BzrDir.open(base, _unsupported=True)
788
def open(base, _unsupported=False, possible_transports=None):
789
"""Open an existing bzrdir, rooted at 'base' (url).
791
:param _unsupported: a private parameter to the BzrDir class.
793
t = get_transport(base, possible_transports=possible_transports)
794
return BzrDir.open_from_transport(t, _unsupported=_unsupported)
797
def open_from_transport(transport, _unsupported=False,
798
_server_formats=True):
799
"""Open a bzrdir within a particular directory.
801
:param transport: Transport containing the bzrdir.
802
:param _unsupported: private.
804
# Keep initial base since 'transport' may be modified while following
806
base = transport.base
807
def find_format(transport):
808
return transport, BzrDirFormat.find_format(
809
transport, _server_formats=_server_formats)
811
def redirected(transport, e, redirection_notice):
812
redirected_transport = transport._redirected_to(e.source, e.target)
813
if redirected_transport is None:
814
raise errors.NotBranchError(base)
815
note('%s is%s redirected to %s',
816
transport.base, e.permanently, redirected_transport.base)
817
return redirected_transport
820
transport, format = do_catching_redirections(find_format,
823
except errors.TooManyRedirections:
824
raise errors.NotBranchError(base)
826
BzrDir._check_supported(format, _unsupported)
827
return format.open(transport, _found=True)
829
def open_branch(self, unsupported=False):
830
"""Open the branch object at this BzrDir if one is present.
832
If unsupported is True, then no longer supported branch formats can
835
TODO: static convenience version of this?
837
raise NotImplementedError(self.open_branch)
840
def open_containing(url, possible_transports=None):
841
"""Open an existing branch which contains url.
843
:param url: url to search from.
844
See open_containing_from_transport for more detail.
846
transport = get_transport(url, possible_transports)
847
return BzrDir.open_containing_from_transport(transport)
850
def open_containing_from_transport(a_transport):
851
"""Open an existing branch which contains a_transport.base.
853
This probes for a branch at a_transport, and searches upwards from there.
855
Basically we keep looking up until we find the control directory or
856
run into the root. If there isn't one, raises NotBranchError.
857
If there is one and it is either an unrecognised format or an unsupported
858
format, UnknownFormatError or UnsupportedFormatError are raised.
859
If there is one, it is returned, along with the unused portion of url.
861
:return: The BzrDir that contains the path, and a Unicode path
862
for the rest of the URL.
864
# this gets the normalised url back. I.e. '.' -> the full path.
865
url = a_transport.base
868
result = BzrDir.open_from_transport(a_transport)
869
return result, urlutils.unescape(a_transport.relpath(url))
870
except errors.NotBranchError, e:
873
new_t = a_transport.clone('..')
874
except errors.InvalidURLJoin:
875
# reached the root, whatever that may be
876
raise errors.NotBranchError(path=url)
877
if new_t.base == a_transport.base:
878
# reached the root, whatever that may be
879
raise errors.NotBranchError(path=url)
882
def _get_tree_branch(self):
883
"""Return the branch and tree, if any, for this bzrdir.
885
Return None for tree if not present or inaccessible.
886
Raise NotBranchError if no branch is present.
887
:return: (tree, branch)
890
tree = self.open_workingtree()
891
except (errors.NoWorkingTree, errors.NotLocalUrl):
893
branch = self.open_branch()
899
def open_tree_or_branch(klass, location):
900
"""Return the branch and working tree at a location.
902
If there is no tree at the location, tree will be None.
903
If there is no branch at the location, an exception will be
905
:return: (tree, branch)
907
bzrdir = klass.open(location)
908
return bzrdir._get_tree_branch()
911
def open_containing_tree_or_branch(klass, location):
912
"""Return the branch and working tree contained by a location.
914
Returns (tree, branch, relpath).
915
If there is no tree at containing the location, tree will be None.
916
If there is no branch containing the location, an exception will be
918
relpath is the portion of the path that is contained by the branch.
920
bzrdir, relpath = klass.open_containing(location)
921
tree, branch = bzrdir._get_tree_branch()
922
return tree, branch, relpath
925
def open_containing_tree_branch_or_repository(klass, location):
926
"""Return the working tree, branch and repo contained by a location.
928
Returns (tree, branch, repository, relpath).
929
If there is no tree containing the location, tree will be None.
930
If there is no branch containing the location, branch will be None.
931
If there is no repository containing the location, repository will be
933
relpath is the portion of the path that is contained by the innermost
936
If no tree, branch or repository is found, a NotBranchError is raised.
938
bzrdir, relpath = klass.open_containing(location)
940
tree, branch = bzrdir._get_tree_branch()
941
except errors.NotBranchError:
943
repo = bzrdir.find_repository()
944
return None, None, repo, relpath
945
except (errors.NoRepositoryPresent):
946
raise errors.NotBranchError(location)
947
return tree, branch, branch.repository, relpath
949
def open_repository(self, _unsupported=False):
950
"""Open the repository object at this BzrDir if one is present.
952
This will not follow the Branch object pointer - it's strictly a direct
953
open facility. Most client code should use open_branch().repository to
956
:param _unsupported: a private parameter, not part of the api.
957
TODO: static convenience version of this?
959
raise NotImplementedError(self.open_repository)
961
def open_workingtree(self, _unsupported=False,
962
recommend_upgrade=True, from_branch=None):
963
"""Open the workingtree object at this BzrDir if one is present.
965
:param recommend_upgrade: Optional keyword parameter, when True (the
966
default), emit through the ui module a recommendation that the user
967
upgrade the working tree when the workingtree being opened is old
968
(but still fully supported).
969
:param from_branch: override bzrdir branch (for lightweight checkouts)
971
raise NotImplementedError(self.open_workingtree)
973
def has_branch(self):
974
"""Tell if this bzrdir contains a branch.
976
Note: if you're going to open the branch, you should just go ahead
977
and try, and not ask permission first. (This method just opens the
978
branch and discards it, and that's somewhat expensive.)
983
except errors.NotBranchError:
986
def has_workingtree(self):
987
"""Tell if this bzrdir contains a working tree.
989
This will still raise an exception if the bzrdir has a workingtree that
990
is remote & inaccessible.
992
Note: if you're going to open the working tree, you should just go ahead
993
and try, and not ask permission first. (This method just opens the
994
workingtree and discards it, and that's somewhat expensive.)
997
self.open_workingtree(recommend_upgrade=False)
999
except errors.NoWorkingTree:
1002
def _cloning_metadir(self):
1003
"""Produce a metadir suitable for cloning with.
1005
:returns: (destination_bzrdir_format, source_repository)
1007
result_format = self._format.__class__()
1010
branch = self.open_branch()
1011
source_repository = branch.repository
1012
result_format._branch_format = branch._format
1013
except errors.NotBranchError:
1014
source_branch = None
1015
source_repository = self.open_repository()
1016
except errors.NoRepositoryPresent:
1017
source_repository = None
1019
# XXX TODO: This isinstance is here because we have not implemented
1020
# the fix recommended in bug # 103195 - to delegate this choice the
1021
# repository itself.
1022
repo_format = source_repository._format
1023
if isinstance(repo_format, remote.RemoteRepositoryFormat):
1024
source_repository._ensure_real()
1025
repo_format = source_repository._real_repository._format
1026
result_format.repository_format = repo_format
1028
# TODO: Couldn't we just probe for the format in these cases,
1029
# rather than opening the whole tree? It would be a little
1030
# faster. mbp 20070401
1031
tree = self.open_workingtree(recommend_upgrade=False)
1032
except (errors.NoWorkingTree, errors.NotLocalUrl):
1033
result_format.workingtree_format = None
1035
result_format.workingtree_format = tree._format.__class__()
1036
return result_format, source_repository
1038
def cloning_metadir(self, require_stacking=False):
1039
"""Produce a metadir suitable for cloning or sprouting with.
1041
These operations may produce workingtrees (yes, even though they're
1042
"cloning" something that doesn't have a tree), so a viable workingtree
1043
format must be selected.
1045
:require_stacking: If True, non-stackable formats will be upgraded
1046
to similar stackable formats.
1047
:returns: a BzrDirFormat with all component formats either set
1048
appropriately or set to None if that component should not be
1051
format, repository = self._cloning_metadir()
1052
if format._workingtree_format is None:
1053
if repository is None:
1055
tree_format = repository._format._matchingbzrdir.workingtree_format
1056
format.workingtree_format = tree_format.__class__()
1057
if require_stacking:
1058
format.require_stacking()
1061
def checkout_metadir(self):
1062
return self.cloning_metadir()
1064
def sprout(self, url, revision_id=None, force_new_repo=False,
1065
recurse='down', possible_transports=None,
1066
accelerator_tree=None, hardlink=False, stacked=False,
1067
source_branch=None, create_tree_if_local=True):
1068
"""Create a copy of this bzrdir prepared for use as a new line of
1071
If url's last component does not exist, it will be created.
1073
Attributes related to the identity of the source branch like
1074
branch nickname will be cleaned, a working tree is created
1075
whether one existed before or not; and a local branch is always
1078
if revision_id is not None, then the clone operation may tune
1079
itself to download less data.
1080
:param accelerator_tree: A tree which can be used for retrieving file
1081
contents more quickly than the revision tree, i.e. a workingtree.
1082
The revision tree will be used for cases where accelerator_tree's
1083
content is different.
1084
:param hardlink: If true, hard-link files from accelerator_tree,
1086
:param stacked: If true, create a stacked branch referring to the
1087
location of this control directory.
1088
:param create_tree_if_local: If true, a working-tree will be created
1089
when working locally.
1091
target_transport = get_transport(url, possible_transports)
1092
target_transport.ensure_base()
1093
cloning_format = self.cloning_metadir(stacked)
1094
# Create/update the result branch
1095
result = cloning_format.initialize_on_transport(target_transport)
1096
# if a stacked branch wasn't requested, we don't create one
1097
# even if the origin was stacked
1098
stacked_branch_url = None
1099
if source_branch is not None:
1101
stacked_branch_url = self.root_transport.base
1102
source_repository = source_branch.repository
1105
source_branch = self.open_branch()
1106
source_repository = source_branch.repository
1108
stacked_branch_url = self.root_transport.base
1109
except errors.NotBranchError:
1110
source_branch = None
1112
source_repository = self.open_repository()
1113
except errors.NoRepositoryPresent:
1114
source_repository = None
1115
repository_policy = result.determine_repository_policy(
1116
force_new_repo, stacked_branch_url, require_stacking=stacked)
1117
result_repo = repository_policy.acquire_repository()
1118
if source_repository is not None:
1119
# Fetch while stacked to prevent unstacked fetch from
1121
result_repo.fetch(source_repository, revision_id=revision_id)
1123
if source_branch is None:
1124
# this is for sprouting a bzrdir without a branch; is that
1126
# Not especially, but it's part of the contract.
1127
result_branch = result.create_branch()
1129
# Force NULL revision to avoid using repository before stacking
1131
result_branch = source_branch.sprout(
1132
result, revision_id=_mod_revision.NULL_REVISION)
1133
parent_location = result_branch.get_parent()
1134
mutter("created new branch %r" % (result_branch,))
1135
repository_policy.configure_branch(result_branch)
1136
if source_branch is not None:
1137
source_branch.copy_content_into(result_branch, revision_id)
1138
# Override copy_content_into
1139
result_branch.set_parent(parent_location)
1141
# Create/update the result working tree
1142
if (create_tree_if_local and
1143
isinstance(target_transport, local.LocalTransport) and
1144
(result_repo is None or result_repo.make_working_trees())):
1145
wt = result.create_workingtree(accelerator_tree=accelerator_tree,
1149
if wt.path2id('') is None:
1151
wt.set_root_id(self.open_workingtree.get_root_id())
1152
except errors.NoWorkingTree:
1158
if recurse == 'down':
1160
basis = wt.basis_tree()
1162
subtrees = basis.iter_references()
1163
elif result_branch is not None:
1164
basis = result_branch.basis_tree()
1166
subtrees = basis.iter_references()
1167
elif source_branch is not None:
1168
basis = source_branch.basis_tree()
1170
subtrees = basis.iter_references()
1175
for path, file_id in subtrees:
1176
target = urlutils.join(url, urlutils.escape(path))
1177
sublocation = source_branch.reference_parent(file_id, path)
1178
sublocation.bzrdir.sprout(target,
1179
basis.get_reference_revision(file_id, path),
1180
force_new_repo=force_new_repo, recurse=recurse,
1183
if basis is not None:
1188
class BzrDirPreSplitOut(BzrDir):
1189
"""A common class for the all-in-one formats."""
1191
def __init__(self, _transport, _format):
1192
"""See BzrDir.__init__."""
1193
super(BzrDirPreSplitOut, self).__init__(_transport, _format)
1194
self._control_files = lockable_files.LockableFiles(
1195
self.get_branch_transport(None),
1196
self._format._lock_file_name,
1197
self._format._lock_class)
1199
def break_lock(self):
1200
"""Pre-splitout bzrdirs do not suffer from stale locks."""
1201
raise NotImplementedError(self.break_lock)
1203
def cloning_metadir(self, require_stacking=False):
1204
"""Produce a metadir suitable for cloning with."""
1205
if require_stacking:
1206
return format_registry.make_bzrdir('1.6')
1207
return self._format.__class__()
1209
def clone(self, url, revision_id=None, force_new_repo=False,
1210
preserve_stacking=False):
1211
"""See BzrDir.clone().
1213
force_new_repo has no effect, since this family of formats always
1214
require a new repository.
1215
preserve_stacking has no effect, since no source branch using this
1216
family of formats can be stacked, so there is no stacking to preserve.
1218
self._make_tail(url)
1219
result = self._format._initialize_for_clone(url)
1220
self.open_repository().clone(result, revision_id=revision_id)
1221
from_branch = self.open_branch()
1222
from_branch.clone(result, revision_id=revision_id)
1224
tree = self.open_workingtree()
1225
except errors.NotLocalUrl:
1226
# make a new one, this format always has to have one.
1227
result._init_workingtree()
1232
def create_branch(self):
1233
"""See BzrDir.create_branch."""
1234
return self._format.get_branch_format().initialize(self)
1236
def destroy_branch(self):
1237
"""See BzrDir.destroy_branch."""
1238
raise errors.UnsupportedOperation(self.destroy_branch, self)
1240
def create_repository(self, shared=False):
1241
"""See BzrDir.create_repository."""
1243
raise errors.IncompatibleFormat('shared repository', self._format)
1244
return self.open_repository()
1246
def destroy_repository(self):
1247
"""See BzrDir.destroy_repository."""
1248
raise errors.UnsupportedOperation(self.destroy_repository, self)
1250
def create_workingtree(self, revision_id=None, from_branch=None,
1251
accelerator_tree=None, hardlink=False):
1252
"""See BzrDir.create_workingtree."""
1253
# The workingtree is sometimes created when the bzrdir is created,
1254
# but not when cloning.
1256
# this looks buggy but is not -really-
1257
# because this format creates the workingtree when the bzrdir is
1259
# clone and sprout will have set the revision_id
1260
# and that will have set it for us, its only
1261
# specific uses of create_workingtree in isolation
1262
# that can do wonky stuff here, and that only
1263
# happens for creating checkouts, which cannot be
1264
# done on this format anyway. So - acceptable wart.
1266
result = self.open_workingtree(recommend_upgrade=False)
1267
except errors.NoSuchFile:
1268
result = self._init_workingtree()
1269
if revision_id is not None:
1270
if revision_id == _mod_revision.NULL_REVISION:
1271
result.set_parent_ids([])
1273
result.set_parent_ids([revision_id])
1276
def _init_workingtree(self):
1277
from bzrlib.workingtree import WorkingTreeFormat2
1279
return WorkingTreeFormat2().initialize(self)
1280
except errors.NotLocalUrl:
1281
# Even though we can't access the working tree, we need to
1282
# create its control files.
1283
return WorkingTreeFormat2()._stub_initialize_on_transport(
1284
self.transport, self._control_files._file_mode)
1286
def destroy_workingtree(self):
1287
"""See BzrDir.destroy_workingtree."""
1288
raise errors.UnsupportedOperation(self.destroy_workingtree, self)
1290
def destroy_workingtree_metadata(self):
1291
"""See BzrDir.destroy_workingtree_metadata."""
1292
raise errors.UnsupportedOperation(self.destroy_workingtree_metadata,
1295
def get_branch_transport(self, branch_format):
1296
"""See BzrDir.get_branch_transport()."""
1297
if branch_format is None:
1298
return self.transport
1300
branch_format.get_format_string()
1301
except NotImplementedError:
1302
return self.transport
1303
raise errors.IncompatibleFormat(branch_format, self._format)
1305
def get_repository_transport(self, repository_format):
1306
"""See BzrDir.get_repository_transport()."""
1307
if repository_format is None:
1308
return self.transport
1310
repository_format.get_format_string()
1311
except NotImplementedError:
1312
return self.transport
1313
raise errors.IncompatibleFormat(repository_format, self._format)
1315
def get_workingtree_transport(self, workingtree_format):
1316
"""See BzrDir.get_workingtree_transport()."""
1317
if workingtree_format is None:
1318
return self.transport
1320
workingtree_format.get_format_string()
1321
except NotImplementedError:
1322
return self.transport
1323
raise errors.IncompatibleFormat(workingtree_format, self._format)
1325
def needs_format_conversion(self, format=None):
1326
"""See BzrDir.needs_format_conversion()."""
1327
# if the format is not the same as the system default,
1328
# an upgrade is needed.
1330
symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
1331
% 'needs_format_conversion(format=None)')
1332
format = BzrDirFormat.get_default_format()
1333
return not isinstance(self._format, format.__class__)
1335
def open_branch(self, unsupported=False):
1336
"""See BzrDir.open_branch."""
1337
from bzrlib.branch import BzrBranchFormat4
1338
format = BzrBranchFormat4()
1339
self._check_supported(format, unsupported)
1340
return format.open(self, _found=True)
1342
def sprout(self, url, revision_id=None, force_new_repo=False,
1343
possible_transports=None, accelerator_tree=None,
1344
hardlink=False, stacked=False, create_tree_if_local=True,
1345
source_branch=None):
1346
"""See BzrDir.sprout()."""
1347
if source_branch is not None:
1348
my_branch = self.open_branch()
1349
if source_branch.base != my_branch.base:
1350
raise AssertionError(
1351
"source branch %r is not within %r with branch %r" %
1352
(source_branch, self, my_branch))
1354
raise errors.UnstackableBranchFormat(
1355
self._format, self.root_transport.base)
1356
if not create_tree_if_local:
1357
raise errors.MustHaveWorkingTree(
1358
self._format, self.root_transport.base)
1359
from bzrlib.workingtree import WorkingTreeFormat2
1360
self._make_tail(url)
1361
result = self._format._initialize_for_clone(url)
1363
self.open_repository().clone(result, revision_id=revision_id)
1364
except errors.NoRepositoryPresent:
1367
self.open_branch().sprout(result, revision_id=revision_id)
1368
except errors.NotBranchError:
1371
# we always want a working tree
1372
WorkingTreeFormat2().initialize(result,
1373
accelerator_tree=accelerator_tree,
1378
class BzrDir4(BzrDirPreSplitOut):
1379
"""A .bzr version 4 control object.
1381
This is a deprecated format and may be removed after sept 2006.
1384
def create_repository(self, shared=False):
1385
"""See BzrDir.create_repository."""
1386
return self._format.repository_format.initialize(self, shared)
1388
def needs_format_conversion(self, format=None):
1389
"""Format 4 dirs are always in need of conversion."""
1391
symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
1392
% 'needs_format_conversion(format=None)')
1395
def open_repository(self):
1396
"""See BzrDir.open_repository."""
1397
from bzrlib.repofmt.weaverepo import RepositoryFormat4
1398
return RepositoryFormat4().open(self, _found=True)
1401
class BzrDir5(BzrDirPreSplitOut):
1402
"""A .bzr version 5 control object.
1404
This is a deprecated format and may be removed after sept 2006.
1407
def open_repository(self):
1408
"""See BzrDir.open_repository."""
1409
from bzrlib.repofmt.weaverepo import RepositoryFormat5
1410
return RepositoryFormat5().open(self, _found=True)
1412
def open_workingtree(self, _unsupported=False,
1413
recommend_upgrade=True):
1414
"""See BzrDir.create_workingtree."""
1415
from bzrlib.workingtree import WorkingTreeFormat2
1416
wt_format = WorkingTreeFormat2()
1417
# we don't warn here about upgrades; that ought to be handled for the
1419
return wt_format.open(self, _found=True)
1422
class BzrDir6(BzrDirPreSplitOut):
1423
"""A .bzr version 6 control object.
1425
This is a deprecated format and may be removed after sept 2006.
1428
def open_repository(self):
1429
"""See BzrDir.open_repository."""
1430
from bzrlib.repofmt.weaverepo import RepositoryFormat6
1431
return RepositoryFormat6().open(self, _found=True)
1433
def open_workingtree(self, _unsupported=False,
1434
recommend_upgrade=True):
1435
"""See BzrDir.create_workingtree."""
1436
# we don't warn here about upgrades; that ought to be handled for the
1438
from bzrlib.workingtree import WorkingTreeFormat2
1439
return WorkingTreeFormat2().open(self, _found=True)
1442
class BzrDirMeta1(BzrDir):
1443
"""A .bzr meta version 1 control object.
1445
This is the first control object where the
1446
individual aspects are really split out: there are separate repository,
1447
workingtree and branch subdirectories and any subset of the three can be
1448
present within a BzrDir.
1451
def can_convert_format(self):
1452
"""See BzrDir.can_convert_format()."""
1455
def create_branch(self):
1456
"""See BzrDir.create_branch."""
1457
return self._format.get_branch_format().initialize(self)
1459
def destroy_branch(self):
1460
"""See BzrDir.create_branch."""
1461
self.transport.delete_tree('branch')
1463
def create_repository(self, shared=False):
1464
"""See BzrDir.create_repository."""
1465
return self._format.repository_format.initialize(self, shared)
1467
def destroy_repository(self):
1468
"""See BzrDir.destroy_repository."""
1469
self.transport.delete_tree('repository')
1471
def create_workingtree(self, revision_id=None, from_branch=None,
1472
accelerator_tree=None, hardlink=False):
1473
"""See BzrDir.create_workingtree."""
1474
return self._format.workingtree_format.initialize(
1475
self, revision_id, from_branch=from_branch,
1476
accelerator_tree=accelerator_tree, hardlink=hardlink)
1478
def destroy_workingtree(self):
1479
"""See BzrDir.destroy_workingtree."""
1480
wt = self.open_workingtree(recommend_upgrade=False)
1481
repository = wt.branch.repository
1482
empty = repository.revision_tree(_mod_revision.NULL_REVISION)
1483
wt.revert(old_tree=empty)
1484
self.destroy_workingtree_metadata()
1486
def destroy_workingtree_metadata(self):
1487
self.transport.delete_tree('checkout')
1489
def find_branch_format(self):
1490
"""Find the branch 'format' for this bzrdir.
1492
This might be a synthetic object for e.g. RemoteBranch and SVN.
1494
from bzrlib.branch import BranchFormat
1495
return BranchFormat.find_format(self)
1497
def _get_mkdir_mode(self):
1498
"""Figure out the mode to use when creating a bzrdir subdir."""
1499
temp_control = lockable_files.LockableFiles(self.transport, '',
1500
lockable_files.TransportLock)
1501
return temp_control._dir_mode
1503
def get_branch_reference(self):
1504
"""See BzrDir.get_branch_reference()."""
1505
from bzrlib.branch import BranchFormat
1506
format = BranchFormat.find_format(self)
1507
return format.get_reference(self)
1509
def get_branch_transport(self, branch_format):
1510
"""See BzrDir.get_branch_transport()."""
1511
if branch_format is None:
1512
return self.transport.clone('branch')
1514
branch_format.get_format_string()
1515
except NotImplementedError:
1516
raise errors.IncompatibleFormat(branch_format, self._format)
1518
self.transport.mkdir('branch', mode=self._get_mkdir_mode())
1519
except errors.FileExists:
1521
return self.transport.clone('branch')
1523
def get_repository_transport(self, repository_format):
1524
"""See BzrDir.get_repository_transport()."""
1525
if repository_format is None:
1526
return self.transport.clone('repository')
1528
repository_format.get_format_string()
1529
except NotImplementedError:
1530
raise errors.IncompatibleFormat(repository_format, self._format)
1532
self.transport.mkdir('repository', mode=self._get_mkdir_mode())
1533
except errors.FileExists:
1535
return self.transport.clone('repository')
1537
def get_workingtree_transport(self, workingtree_format):
1538
"""See BzrDir.get_workingtree_transport()."""
1539
if workingtree_format is None:
1540
return self.transport.clone('checkout')
1542
workingtree_format.get_format_string()
1543
except NotImplementedError:
1544
raise errors.IncompatibleFormat(workingtree_format, self._format)
1546
self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
1547
except errors.FileExists:
1549
return self.transport.clone('checkout')
1551
def needs_format_conversion(self, format=None):
1552
"""See BzrDir.needs_format_conversion()."""
1554
symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
1555
% 'needs_format_conversion(format=None)')
1557
format = BzrDirFormat.get_default_format()
1558
if not isinstance(self._format, format.__class__):
1559
# it is not a meta dir format, conversion is needed.
1561
# we might want to push this down to the repository?
1563
if not isinstance(self.open_repository()._format,
1564
format.repository_format.__class__):
1565
# the repository needs an upgrade.
1567
except errors.NoRepositoryPresent:
1570
if not isinstance(self.open_branch()._format,
1571
format.get_branch_format().__class__):
1572
# the branch needs an upgrade.
1574
except errors.NotBranchError:
1577
my_wt = self.open_workingtree(recommend_upgrade=False)
1578
if not isinstance(my_wt._format,
1579
format.workingtree_format.__class__):
1580
# the workingtree needs an upgrade.
1582
except (errors.NoWorkingTree, errors.NotLocalUrl):
1586
def open_branch(self, unsupported=False):
1587
"""See BzrDir.open_branch."""
1588
format = self.find_branch_format()
1589
self._check_supported(format, unsupported)
1590
return format.open(self, _found=True)
1592
def open_repository(self, unsupported=False):
1593
"""See BzrDir.open_repository."""
1594
from bzrlib.repository import RepositoryFormat
1595
format = RepositoryFormat.find_format(self)
1596
self._check_supported(format, unsupported)
1597
return format.open(self, _found=True)
1599
def open_workingtree(self, unsupported=False,
1600
recommend_upgrade=True):
1601
"""See BzrDir.open_workingtree."""
1602
from bzrlib.workingtree import WorkingTreeFormat
1603
format = WorkingTreeFormat.find_format(self)
1604
self._check_supported(format, unsupported,
1606
basedir=self.root_transport.base)
1607
return format.open(self, _found=True)
1609
def _get_config(self):
1610
return config.BzrDirConfig(self.transport)
1613
class BzrDirFormat(object):
1614
"""An encapsulation of the initialization and open routines for a format.
1616
Formats provide three things:
1617
* An initialization routine,
1621
Formats are placed in a dict by their format string for reference
1622
during bzrdir opening. These should be subclasses of BzrDirFormat
1625
Once a format is deprecated, just deprecate the initialize and open
1626
methods on the format class. Do not deprecate the object, as the
1627
object will be created every system load.
1630
_default_format = None
1631
"""The default format used for new .bzr dirs."""
1634
"""The known formats."""
1636
_control_formats = []
1637
"""The registered control formats - .bzr, ....
1639
This is a list of BzrDirFormat objects.
1642
_control_server_formats = []
1643
"""The registered control server formats, e.g. RemoteBzrDirs.
1645
This is a list of BzrDirFormat objects.
1648
_lock_file_name = 'branch-lock'
1650
# _lock_class must be set in subclasses to the lock type, typ.
1651
# TransportLock or LockDir
1654
def find_format(klass, transport, _server_formats=True):
1655
"""Return the format present at transport."""
1657
formats = klass._control_server_formats + klass._control_formats
1659
formats = klass._control_formats
1660
for format in formats:
1662
return format.probe_transport(transport)
1663
except errors.NotBranchError:
1664
# this format does not find a control dir here.
1666
raise errors.NotBranchError(path=transport.base)
1669
def probe_transport(klass, transport):
1670
"""Return the .bzrdir style format present in a directory."""
1672
format_string = transport.get(".bzr/branch-format").read()
1673
except errors.NoSuchFile:
1674
raise errors.NotBranchError(path=transport.base)
1677
return klass._formats[format_string]
1679
raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
1682
def get_default_format(klass):
1683
"""Return the current default format."""
1684
return klass._default_format
1686
def get_format_string(self):
1687
"""Return the ASCII format string that identifies this format."""
1688
raise NotImplementedError(self.get_format_string)
1690
def get_format_description(self):
1691
"""Return the short description for this format."""
1692
raise NotImplementedError(self.get_format_description)
1694
def get_converter(self, format=None):
1695
"""Return the converter to use to convert bzrdirs needing converts.
1697
This returns a bzrlib.bzrdir.Converter object.
1699
This should return the best upgrader to step this format towards the
1700
current default format. In the case of plugins we can/should provide
1701
some means for them to extend the range of returnable converters.
1703
:param format: Optional format to override the default format of the
1706
raise NotImplementedError(self.get_converter)
1708
def initialize(self, url, possible_transports=None):
1709
"""Create a bzr control dir at this url and return an opened copy.
1711
Subclasses should typically override initialize_on_transport
1712
instead of this method.
1714
return self.initialize_on_transport(get_transport(url,
1715
possible_transports))
1717
def initialize_on_transport(self, transport):
1718
"""Initialize a new bzrdir in the base directory of a Transport."""
1720
# can we hand off the request to the smart server rather than using
1722
client_medium = transport.get_smart_medium()
1723
except errors.NoSmartMedium:
1724
return self._initialize_on_transport_vfs(transport)
1726
# Current RPC's only know how to create bzr metadir1 instances, so
1727
# we still delegate to vfs methods if the requested format is not a
1729
if type(self) != BzrDirMetaFormat1:
1730
return self._initialize_on_transport_vfs(transport)
1731
remote_format = RemoteBzrDirFormat()
1732
self._supply_sub_formats_to(remote_format)
1733
return remote_format.initialize_on_transport(transport)
1735
def _initialize_on_transport_vfs(self, transport):
1736
"""Initialize a new bzrdir using VFS calls.
1738
:param transport: The transport to create the .bzr directory in.
1741
# Since we are creating a .bzr directory, inherit the
1742
# mode from the root directory
1743
temp_control = lockable_files.LockableFiles(transport,
1744
'', lockable_files.TransportLock)
1745
temp_control._transport.mkdir('.bzr',
1746
# FIXME: RBC 20060121 don't peek under
1748
mode=temp_control._dir_mode)
1749
if sys.platform == 'win32' and isinstance(transport, local.LocalTransport):
1750
win32utils.set_file_attr_hidden(transport._abspath('.bzr'))
1751
file_mode = temp_control._file_mode
1753
bzrdir_transport = transport.clone('.bzr')
1754
utf8_files = [('README',
1755
"This is a Bazaar control directory.\n"
1756
"Do not change any files in this directory.\n"
1757
"See http://bazaar-vcs.org/ for more information about Bazaar.\n"),
1758
('branch-format', self.get_format_string()),
1760
# NB: no need to escape relative paths that are url safe.
1761
control_files = lockable_files.LockableFiles(bzrdir_transport,
1762
self._lock_file_name, self._lock_class)
1763
control_files.create_lock()
1764
control_files.lock_write()
1766
for (filename, content) in utf8_files:
1767
bzrdir_transport.put_bytes(filename, content,
1770
control_files.unlock()
1771
return self.open(transport, _found=True)
1773
def is_supported(self):
1774
"""Is this format supported?
1776
Supported formats must be initializable and openable.
1777
Unsupported formats may not support initialization or committing or
1778
some other features depending on the reason for not being supported.
1782
def network_name(self):
1783
"""A simple byte string uniquely identifying this format for RPC calls.
1785
Bzr control formats use thir disk format string to identify the format
1786
over the wire. Its possible that other control formats have more
1787
complex detection requirements, so we permit them to use any unique and
1788
immutable string they desire.
1790
raise NotImplementedError(self.network_name)
1792
def same_model(self, target_format):
1793
return (self.repository_format.rich_root_data ==
1794
target_format.rich_root_data)
1797
def known_formats(klass):
1798
"""Return all the known formats.
1800
Concrete formats should override _known_formats.
1802
# There is double indirection here to make sure that control
1803
# formats used by more than one dir format will only be probed
1804
# once. This can otherwise be quite expensive for remote connections.
1806
for format in klass._control_formats:
1807
result.update(format._known_formats())
1811
def _known_formats(klass):
1812
"""Return the known format instances for this control format."""
1813
return set(klass._formats.values())
1815
def open(self, transport, _found=False):
1816
"""Return an instance of this format for the dir transport points at.
1818
_found is a private parameter, do not use it.
1821
found_format = BzrDirFormat.find_format(transport)
1822
if not isinstance(found_format, self.__class__):
1823
raise AssertionError("%s was asked to open %s, but it seems to need "
1825
% (self, transport, found_format))
1826
# Allow subclasses - use the found format.
1827
self._supply_sub_formats_to(found_format)
1828
return found_format._open(transport)
1829
return self._open(transport)
1831
def _open(self, transport):
1832
"""Template method helper for opening BzrDirectories.
1834
This performs the actual open and any additional logic or parameter
1837
raise NotImplementedError(self._open)
1840
def register_format(klass, format):
1841
klass._formats[format.get_format_string()] = format
1842
# bzr native formats have a network name of their format string.
1843
network_format_registry.register(format.get_format_string(), format)
1846
def register_control_format(klass, format):
1847
"""Register a format that does not use '.bzr' for its control dir.
1849
TODO: This should be pulled up into a 'ControlDirFormat' base class
1850
which BzrDirFormat can inherit from, and renamed to register_format
1851
there. It has been done without that for now for simplicity of
1854
klass._control_formats.append(format)
1857
def register_control_server_format(klass, format):
1858
"""Register a control format for client-server environments.
1860
These formats will be tried before ones registered with
1861
register_control_format. This gives implementations that decide to the
1862
chance to grab it before anything looks at the contents of the format
1865
klass._control_server_formats.append(format)
1868
def _set_default_format(klass, format):
1869
"""Set default format (for testing behavior of defaults only)"""
1870
klass._default_format = format
1874
return self.get_format_description().rstrip()
1876
def _supply_sub_formats_to(self, other_format):
1877
"""Give other_format the same values for sub formats as this has.
1879
This method is expected to be used when parameterising a
1880
RemoteBzrDirFormat instance with the parameters from a
1881
BzrDirMetaFormat1 instance.
1883
:param other_format: other_format is a format which should be
1884
compatible with whatever sub formats are supported by self.
1889
def unregister_format(klass, format):
1890
del klass._formats[format.get_format_string()]
1893
def unregister_control_format(klass, format):
1894
klass._control_formats.remove(format)
1897
class BzrDirFormat4(BzrDirFormat):
1898
"""Bzr dir format 4.
1900
This format is a combined format for working tree, branch and repository.
1902
- Format 1 working trees [always]
1903
- Format 4 branches [always]
1904
- Format 4 repositories [always]
1906
This format is deprecated: it indexes texts using a text it which is
1907
removed in format 5; write support for this format has been removed.
1910
_lock_class = lockable_files.TransportLock
1912
def get_format_string(self):
1913
"""See BzrDirFormat.get_format_string()."""
1914
return "Bazaar-NG branch, format 0.0.4\n"
1916
def get_format_description(self):
1917
"""See BzrDirFormat.get_format_description()."""
1918
return "All-in-one format 4"
1920
def get_converter(self, format=None):
1921
"""See BzrDirFormat.get_converter()."""
1922
# there is one and only one upgrade path here.
1923
return ConvertBzrDir4To5()
1925
def initialize_on_transport(self, transport):
1926
"""Format 4 branches cannot be created."""
1927
raise errors.UninitializableFormat(self)
1929
def is_supported(self):
1930
"""Format 4 is not supported.
1932
It is not supported because the model changed from 4 to 5 and the
1933
conversion logic is expensive - so doing it on the fly was not
1938
def network_name(self):
1939
return self.get_format_string()
1941
def _open(self, transport):
1942
"""See BzrDirFormat._open."""
1943
return BzrDir4(transport, self)
1945
def __return_repository_format(self):
1946
"""Circular import protection."""
1947
from bzrlib.repofmt.weaverepo import RepositoryFormat4
1948
return RepositoryFormat4()
1949
repository_format = property(__return_repository_format)
1952
class BzrDirFormat5(BzrDirFormat):
1953
"""Bzr control format 5.
1955
This format is a combined format for working tree, branch and repository.
1957
- Format 2 working trees [always]
1958
- Format 4 branches [always]
1959
- Format 5 repositories [always]
1960
Unhashed stores in the repository.
1963
_lock_class = lockable_files.TransportLock
1965
def get_format_string(self):
1966
"""See BzrDirFormat.get_format_string()."""
1967
return "Bazaar-NG branch, format 5\n"
1969
def get_branch_format(self):
1970
from bzrlib import branch
1971
return branch.BzrBranchFormat4()
1973
def get_format_description(self):
1974
"""See BzrDirFormat.get_format_description()."""
1975
return "All-in-one format 5"
1977
def get_converter(self, format=None):
1978
"""See BzrDirFormat.get_converter()."""
1979
# there is one and only one upgrade path here.
1980
return ConvertBzrDir5To6()
1982
def _initialize_for_clone(self, url):
1983
return self.initialize_on_transport(get_transport(url), _cloning=True)
1985
def initialize_on_transport(self, transport, _cloning=False):
1986
"""Format 5 dirs always have working tree, branch and repository.
1988
Except when they are being cloned.
1990
from bzrlib.branch import BzrBranchFormat4
1991
from bzrlib.repofmt.weaverepo import RepositoryFormat5
1992
result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
1993
RepositoryFormat5().initialize(result, _internal=True)
1995
branch = BzrBranchFormat4().initialize(result)
1996
result._init_workingtree()
1999
def network_name(self):
2000
return self.get_format_string()
2002
def _open(self, transport):
2003
"""See BzrDirFormat._open."""
2004
return BzrDir5(transport, self)
2006
def __return_repository_format(self):
2007
"""Circular import protection."""
2008
from bzrlib.repofmt.weaverepo import RepositoryFormat5
2009
return RepositoryFormat5()
2010
repository_format = property(__return_repository_format)
2013
class BzrDirFormat6(BzrDirFormat):
2014
"""Bzr control format 6.
2016
This format is a combined format for working tree, branch and repository.
2018
- Format 2 working trees [always]
2019
- Format 4 branches [always]
2020
- Format 6 repositories [always]
2023
_lock_class = lockable_files.TransportLock
2025
def get_format_string(self):
2026
"""See BzrDirFormat.get_format_string()."""
2027
return "Bazaar-NG branch, format 6\n"
2029
def get_format_description(self):
2030
"""See BzrDirFormat.get_format_description()."""
2031
return "All-in-one format 6"
2033
def get_branch_format(self):
2034
from bzrlib import branch
2035
return branch.BzrBranchFormat4()
2037
def get_converter(self, format=None):
2038
"""See BzrDirFormat.get_converter()."""
2039
# there is one and only one upgrade path here.
2040
return ConvertBzrDir6ToMeta()
2042
def _initialize_for_clone(self, url):
2043
return self.initialize_on_transport(get_transport(url), _cloning=True)
2045
def initialize_on_transport(self, transport, _cloning=False):
2046
"""Format 6 dirs always have working tree, branch and repository.
2048
Except when they are being cloned.
2050
from bzrlib.branch import BzrBranchFormat4
2051
from bzrlib.repofmt.weaverepo import RepositoryFormat6
2052
result = super(BzrDirFormat6, self).initialize_on_transport(transport)
2053
RepositoryFormat6().initialize(result, _internal=True)
2055
branch = BzrBranchFormat4().initialize(result)
2056
result._init_workingtree()
2059
def network_name(self):
2060
return self.get_format_string()
2062
def _open(self, transport):
2063
"""See BzrDirFormat._open."""
2064
return BzrDir6(transport, self)
2066
def __return_repository_format(self):
2067
"""Circular import protection."""
2068
from bzrlib.repofmt.weaverepo import RepositoryFormat6
2069
return RepositoryFormat6()
2070
repository_format = property(__return_repository_format)
2073
class BzrDirMetaFormat1(BzrDirFormat):
2074
"""Bzr meta control format 1
2076
This is the first format with split out working tree, branch and repository
2079
- Format 3 working trees [optional]
2080
- Format 5 branches [optional]
2081
- Format 7 repositories [optional]
2084
_lock_class = lockdir.LockDir
2087
self._workingtree_format = None
2088
self._branch_format = None
2089
self._repository_format = None
2091
def __eq__(self, other):
2092
if other.__class__ is not self.__class__:
2094
if other.repository_format != self.repository_format:
2096
if other.workingtree_format != self.workingtree_format:
2100
def __ne__(self, other):
2101
return not self == other
2103
def get_branch_format(self):
2104
if self._branch_format is None:
2105
from bzrlib.branch import BranchFormat
2106
self._branch_format = BranchFormat.get_default_format()
2107
return self._branch_format
2109
def set_branch_format(self, format):
2110
self._branch_format = format
2112
def require_stacking(self):
2113
if not self.get_branch_format().supports_stacking():
2114
# We need to make a stacked branch, but the default format for the
2115
# target doesn't support stacking. So force a branch that *can*
2117
from bzrlib.branch import BzrBranchFormat7
2118
branch_format = BzrBranchFormat7()
2119
self.set_branch_format(branch_format)
2120
mutter("using %r for stacking" % (branch_format,))
2121
from bzrlib.repofmt import pack_repo
2122
if self.repository_format.rich_root_data:
2123
bzrdir_format_name = '1.6.1-rich-root'
2124
repo_format = pack_repo.RepositoryFormatKnitPack5RichRoot()
2126
bzrdir_format_name = '1.6'
2127
repo_format = pack_repo.RepositoryFormatKnitPack5()
2128
note('Source format does not support stacking, using format:'
2130
bzrdir_format_name, repo_format.get_format_description())
2131
self.repository_format = repo_format
2133
def get_converter(self, format=None):
2134
"""See BzrDirFormat.get_converter()."""
2136
format = BzrDirFormat.get_default_format()
2137
if not isinstance(self, format.__class__):
2138
# converting away from metadir is not implemented
2139
raise NotImplementedError(self.get_converter)
2140
return ConvertMetaToMeta(format)
2142
def get_format_string(self):
2143
"""See BzrDirFormat.get_format_string()."""
2144
return "Bazaar-NG meta directory, format 1\n"
2146
def get_format_description(self):
2147
"""See BzrDirFormat.get_format_description()."""
2148
return "Meta directory format 1"
2150
def network_name(self):
2151
return self.get_format_string()
2153
def _open(self, transport):
2154
"""See BzrDirFormat._open."""
2155
return BzrDirMeta1(transport, self)
2157
def __return_repository_format(self):
2158
"""Circular import protection."""
2159
if self._repository_format:
2160
return self._repository_format
2161
from bzrlib.repository import RepositoryFormat
2162
return RepositoryFormat.get_default_format()
2164
def _set_repository_format(self, value):
2165
"""Allow changing the repository format for metadir formats."""
2166
self._repository_format = value
2168
repository_format = property(__return_repository_format,
2169
_set_repository_format)
2171
def _supply_sub_formats_to(self, other_format):
2172
"""Give other_format the same values for sub formats as this has.
2174
This method is expected to be used when parameterising a
2175
RemoteBzrDirFormat instance with the parameters from a
2176
BzrDirMetaFormat1 instance.
2178
:param other_format: other_format is a format which should be
2179
compatible with whatever sub formats are supported by self.
2182
if getattr(self, '_repository_format', None) is not None:
2183
other_format.repository_format = self.repository_format
2184
if self._branch_format is not None:
2185
other_format._branch_format = self._branch_format
2186
if self._workingtree_format is not None:
2187
other_format.workingtree_format = self.workingtree_format
2189
def __get_workingtree_format(self):
2190
if self._workingtree_format is None:
2191
from bzrlib.workingtree import WorkingTreeFormat
2192
self._workingtree_format = WorkingTreeFormat.get_default_format()
2193
return self._workingtree_format
2195
def __set_workingtree_format(self, wt_format):
2196
self._workingtree_format = wt_format
2198
workingtree_format = property(__get_workingtree_format,
2199
__set_workingtree_format)
2202
network_format_registry = registry.FormatRegistry()
2203
"""Registry of formats indexed by their network name.
2205
The network name for a BzrDirFormat is an identifier that can be used when
2206
referring to formats with smart server operations. See
2207
BzrDirFormat.network_name() for more detail.
2211
# Register bzr control format
2212
BzrDirFormat.register_control_format(BzrDirFormat)
2214
# Register bzr formats
2215
BzrDirFormat.register_format(BzrDirFormat4())
2216
BzrDirFormat.register_format(BzrDirFormat5())
2217
BzrDirFormat.register_format(BzrDirFormat6())
2218
__default_format = BzrDirMetaFormat1()
2219
BzrDirFormat.register_format(__default_format)
2220
BzrDirFormat._default_format = __default_format
2223
class Converter(object):
2224
"""Converts a disk format object from one format to another."""
2226
def convert(self, to_convert, pb):
2227
"""Perform the conversion of to_convert, giving feedback via pb.
2229
:param to_convert: The disk object to convert.
2230
:param pb: a progress bar to use for progress information.
2233
def step(self, message):
2234
"""Update the pb by a step."""
2236
self.pb.update(message, self.count, self.total)
2239
class ConvertBzrDir4To5(Converter):
2240
"""Converts format 4 bzr dirs to format 5."""
2243
super(ConvertBzrDir4To5, self).__init__()
2244
self.converted_revs = set()
2245
self.absent_revisions = set()
2249
def convert(self, to_convert, pb):
2250
"""See Converter.convert()."""
2251
self.bzrdir = to_convert
2253
self.pb.note('starting upgrade from format 4 to 5')
2254
if isinstance(self.bzrdir.transport, local.LocalTransport):
2255
self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
2256
self._convert_to_weaves()
2257
return BzrDir.open(self.bzrdir.root_transport.base)
2259
def _convert_to_weaves(self):
2260
self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
2263
stat = self.bzrdir.transport.stat('weaves')
2264
if not S_ISDIR(stat.st_mode):
2265
self.bzrdir.transport.delete('weaves')
2266
self.bzrdir.transport.mkdir('weaves')
2267
except errors.NoSuchFile:
2268
self.bzrdir.transport.mkdir('weaves')
2269
# deliberately not a WeaveFile as we want to build it up slowly.
2270
self.inv_weave = Weave('inventory')
2271
# holds in-memory weaves for all files
2272
self.text_weaves = {}
2273
self.bzrdir.transport.delete('branch-format')
2274
self.branch = self.bzrdir.open_branch()
2275
self._convert_working_inv()
2276
rev_history = self.branch.revision_history()
2277
# to_read is a stack holding the revisions we still need to process;
2278
# appending to it adds new highest-priority revisions
2279
self.known_revisions = set(rev_history)
2280
self.to_read = rev_history[-1:]
2282
rev_id = self.to_read.pop()
2283
if (rev_id not in self.revisions
2284
and rev_id not in self.absent_revisions):
2285
self._load_one_rev(rev_id)
2287
to_import = self._make_order()
2288
for i, rev_id in enumerate(to_import):
2289
self.pb.update('converting revision', i, len(to_import))
2290
self._convert_one_rev(rev_id)
2292
self._write_all_weaves()
2293
self._write_all_revs()
2294
self.pb.note('upgraded to weaves:')
2295
self.pb.note(' %6d revisions and inventories', len(self.revisions))
2296
self.pb.note(' %6d revisions not present', len(self.absent_revisions))
2297
self.pb.note(' %6d texts', self.text_count)
2298
self._cleanup_spare_files_after_format4()
2299
self.branch._transport.put_bytes(
2301
BzrDirFormat5().get_format_string(),
2302
mode=self.bzrdir._get_file_mode())
2304
def _cleanup_spare_files_after_format4(self):
2305
# FIXME working tree upgrade foo.
2306
for n in 'merged-patches', 'pending-merged-patches':
2308
## assert os.path.getsize(p) == 0
2309
self.bzrdir.transport.delete(n)
2310
except errors.NoSuchFile:
2312
self.bzrdir.transport.delete_tree('inventory-store')
2313
self.bzrdir.transport.delete_tree('text-store')
2315
def _convert_working_inv(self):
2316
inv = xml4.serializer_v4.read_inventory(
2317
self.branch._transport.get('inventory'))
2318
new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
2319
self.branch._transport.put_bytes('inventory', new_inv_xml,
2320
mode=self.bzrdir._get_file_mode())
2322
def _write_all_weaves(self):
2323
controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
2324
weave_transport = self.bzrdir.transport.clone('weaves')
2325
weaves = WeaveStore(weave_transport, prefixed=False)
2326
transaction = WriteTransaction()
2330
for file_id, file_weave in self.text_weaves.items():
2331
self.pb.update('writing weave', i, len(self.text_weaves))
2332
weaves._put_weave(file_id, file_weave, transaction)
2334
self.pb.update('inventory', 0, 1)
2335
controlweaves._put_weave('inventory', self.inv_weave, transaction)
2336
self.pb.update('inventory', 1, 1)
2340
def _write_all_revs(self):
2341
"""Write all revisions out in new form."""
2342
self.bzrdir.transport.delete_tree('revision-store')
2343
self.bzrdir.transport.mkdir('revision-store')
2344
revision_transport = self.bzrdir.transport.clone('revision-store')
2346
from bzrlib.xml5 import serializer_v5
2347
from bzrlib.repofmt.weaverepo import RevisionTextStore
2348
revision_store = RevisionTextStore(revision_transport,
2349
serializer_v5, False, versionedfile.PrefixMapper(),
2350
lambda:True, lambda:True)
2352
for i, rev_id in enumerate(self.converted_revs):
2353
self.pb.update('write revision', i, len(self.converted_revs))
2354
text = serializer_v5.write_revision_to_string(
2355
self.revisions[rev_id])
2357
revision_store.add_lines(key, None, osutils.split_lines(text))
2361
def _load_one_rev(self, rev_id):
2362
"""Load a revision object into memory.
2364
Any parents not either loaded or abandoned get queued to be
2366
self.pb.update('loading revision',
2367
len(self.revisions),
2368
len(self.known_revisions))
2369
if not self.branch.repository.has_revision(rev_id):
2371
self.pb.note('revision {%s} not present in branch; '
2372
'will be converted as a ghost',
2374
self.absent_revisions.add(rev_id)
2376
rev = self.branch.repository.get_revision(rev_id)
2377
for parent_id in rev.parent_ids:
2378
self.known_revisions.add(parent_id)
2379
self.to_read.append(parent_id)
2380
self.revisions[rev_id] = rev
2382
def _load_old_inventory(self, rev_id):
2383
old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
2384
inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
2385
inv.revision_id = rev_id
2386
rev = self.revisions[rev_id]
2389
def _load_updated_inventory(self, rev_id):
2390
inv_xml = self.inv_weave.get_text(rev_id)
2391
inv = xml5.serializer_v5.read_inventory_from_string(inv_xml, rev_id)
2394
def _convert_one_rev(self, rev_id):
2395
"""Convert revision and all referenced objects to new format."""
2396
rev = self.revisions[rev_id]
2397
inv = self._load_old_inventory(rev_id)
2398
present_parents = [p for p in rev.parent_ids
2399
if p not in self.absent_revisions]
2400
self._convert_revision_contents(rev, inv, present_parents)
2401
self._store_new_inv(rev, inv, present_parents)
2402
self.converted_revs.add(rev_id)
2404
def _store_new_inv(self, rev, inv, present_parents):
2405
new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
2406
new_inv_sha1 = sha_string(new_inv_xml)
2407
self.inv_weave.add_lines(rev.revision_id,
2409
new_inv_xml.splitlines(True))
2410
rev.inventory_sha1 = new_inv_sha1
2412
def _convert_revision_contents(self, rev, inv, present_parents):
2413
"""Convert all the files within a revision.
2415
Also upgrade the inventory to refer to the text revision ids."""
2416
rev_id = rev.revision_id
2417
mutter('converting texts of revision {%s}',
2419
parent_invs = map(self._load_updated_inventory, present_parents)
2420
entries = inv.iter_entries()
2422
for path, ie in entries:
2423
self._convert_file_version(rev, ie, parent_invs)
2425
def _convert_file_version(self, rev, ie, parent_invs):
2426
"""Convert one version of one file.
2428
The file needs to be added into the weave if it is a merge
2429
of >=2 parents or if it's changed from its parent.
2431
file_id = ie.file_id
2432
rev_id = rev.revision_id
2433
w = self.text_weaves.get(file_id)
2436
self.text_weaves[file_id] = w
2437
text_changed = False
2438
parent_candiate_entries = ie.parent_candidates(parent_invs)
2439
heads = graph.Graph(self).heads(parent_candiate_entries.keys())
2440
# XXX: Note that this is unordered - and this is tolerable because
2441
# the previous code was also unordered.
2442
previous_entries = dict((head, parent_candiate_entries[head]) for head
2444
self.snapshot_ie(previous_entries, ie, w, rev_id)
2447
@symbol_versioning.deprecated_method(symbol_versioning.one_one)
2448
def get_parents(self, revision_ids):
2449
for revision_id in revision_ids:
2450
yield self.revisions[revision_id].parent_ids
2452
def get_parent_map(self, revision_ids):
2453
"""See graph._StackedParentsProvider.get_parent_map"""
2454
return dict((revision_id, self.revisions[revision_id])
2455
for revision_id in revision_ids
2456
if revision_id in self.revisions)
2458
def snapshot_ie(self, previous_revisions, ie, w, rev_id):
2459
# TODO: convert this logic, which is ~= snapshot to
2460
# a call to:. This needs the path figured out. rather than a work_tree
2461
# a v4 revision_tree can be given, or something that looks enough like
2462
# one to give the file content to the entry if it needs it.
2463
# and we need something that looks like a weave store for snapshot to
2465
#ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
2466
if len(previous_revisions) == 1:
2467
previous_ie = previous_revisions.values()[0]
2468
if ie._unchanged(previous_ie):
2469
ie.revision = previous_ie.revision
2472
text = self.branch.repository._text_store.get(ie.text_id)
2473
file_lines = text.readlines()
2474
w.add_lines(rev_id, previous_revisions, file_lines)
2475
self.text_count += 1
2477
w.add_lines(rev_id, previous_revisions, [])
2478
ie.revision = rev_id
2480
def _make_order(self):
2481
"""Return a suitable order for importing revisions.
2483
The order must be such that an revision is imported after all
2484
its (present) parents.
2486
todo = set(self.revisions.keys())
2487
done = self.absent_revisions.copy()
2490
# scan through looking for a revision whose parents
2492
for rev_id in sorted(list(todo)):
2493
rev = self.revisions[rev_id]
2494
parent_ids = set(rev.parent_ids)
2495
if parent_ids.issubset(done):
2496
# can take this one now
2497
order.append(rev_id)
2503
class ConvertBzrDir5To6(Converter):
2504
"""Converts format 5 bzr dirs to format 6."""
2506
def convert(self, to_convert, pb):
2507
"""See Converter.convert()."""
2508
self.bzrdir = to_convert
2510
self.pb.note('starting upgrade from format 5 to 6')
2511
self._convert_to_prefixed()
2512
return BzrDir.open(self.bzrdir.root_transport.base)
2514
def _convert_to_prefixed(self):
2515
from bzrlib.store import TransportStore
2516
self.bzrdir.transport.delete('branch-format')
2517
for store_name in ["weaves", "revision-store"]:
2518
self.pb.note("adding prefixes to %s" % store_name)
2519
store_transport = self.bzrdir.transport.clone(store_name)
2520
store = TransportStore(store_transport, prefixed=True)
2521
for urlfilename in store_transport.list_dir('.'):
2522
filename = urlutils.unescape(urlfilename)
2523
if (filename.endswith(".weave") or
2524
filename.endswith(".gz") or
2525
filename.endswith(".sig")):
2526
file_id, suffix = os.path.splitext(filename)
2530
new_name = store._mapper.map((file_id,)) + suffix
2531
# FIXME keep track of the dirs made RBC 20060121
2533
store_transport.move(filename, new_name)
2534
except errors.NoSuchFile: # catches missing dirs strangely enough
2535
store_transport.mkdir(osutils.dirname(new_name))
2536
store_transport.move(filename, new_name)
2537
self.bzrdir.transport.put_bytes(
2539
BzrDirFormat6().get_format_string(),
2540
mode=self.bzrdir._get_file_mode())
2543
class ConvertBzrDir6ToMeta(Converter):
2544
"""Converts format 6 bzr dirs to metadirs."""
2546
def convert(self, to_convert, pb):
2547
"""See Converter.convert()."""
2548
from bzrlib.repofmt.weaverepo import RepositoryFormat7
2549
from bzrlib.branch import BzrBranchFormat5
2550
self.bzrdir = to_convert
2553
self.total = 20 # the steps we know about
2554
self.garbage_inventories = []
2555
self.dir_mode = self.bzrdir._get_dir_mode()
2556
self.file_mode = self.bzrdir._get_file_mode()
2558
self.pb.note('starting upgrade from format 6 to metadir')
2559
self.bzrdir.transport.put_bytes(
2561
"Converting to format 6",
2562
mode=self.file_mode)
2563
# its faster to move specific files around than to open and use the apis...
2564
# first off, nuke ancestry.weave, it was never used.
2566
self.step('Removing ancestry.weave')
2567
self.bzrdir.transport.delete('ancestry.weave')
2568
except errors.NoSuchFile:
2570
# find out whats there
2571
self.step('Finding branch files')
2572
last_revision = self.bzrdir.open_branch().last_revision()
2573
bzrcontents = self.bzrdir.transport.list_dir('.')
2574
for name in bzrcontents:
2575
if name.startswith('basis-inventory.'):
2576
self.garbage_inventories.append(name)
2577
# create new directories for repository, working tree and branch
2578
repository_names = [('inventory.weave', True),
2579
('revision-store', True),
2581
self.step('Upgrading repository ')
2582
self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
2583
self.make_lock('repository')
2584
# we hard code the formats here because we are converting into
2585
# the meta format. The meta format upgrader can take this to a
2586
# future format within each component.
2587
self.put_format('repository', RepositoryFormat7())
2588
for entry in repository_names:
2589
self.move_entry('repository', entry)
2591
self.step('Upgrading branch ')
2592
self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
2593
self.make_lock('branch')
2594
self.put_format('branch', BzrBranchFormat5())
2595
branch_files = [('revision-history', True),
2596
('branch-name', True),
2598
for entry in branch_files:
2599
self.move_entry('branch', entry)
2601
checkout_files = [('pending-merges', True),
2602
('inventory', True),
2603
('stat-cache', False)]
2604
# If a mandatory checkout file is not present, the branch does not have
2605
# a functional checkout. Do not create a checkout in the converted
2607
for name, mandatory in checkout_files:
2608
if mandatory and name not in bzrcontents:
2609
has_checkout = False
2613
if not has_checkout:
2614
self.pb.note('No working tree.')
2615
# If some checkout files are there, we may as well get rid of them.
2616
for name, mandatory in checkout_files:
2617
if name in bzrcontents:
2618
self.bzrdir.transport.delete(name)
2620
from bzrlib.workingtree import WorkingTreeFormat3
2621
self.step('Upgrading working tree')
2622
self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
2623
self.make_lock('checkout')
2625
'checkout', WorkingTreeFormat3())
2626
self.bzrdir.transport.delete_multi(
2627
self.garbage_inventories, self.pb)
2628
for entry in checkout_files:
2629
self.move_entry('checkout', entry)
2630
if last_revision is not None:
2631
self.bzrdir.transport.put_bytes(
2632
'checkout/last-revision', last_revision)
2633
self.bzrdir.transport.put_bytes(
2635
BzrDirMetaFormat1().get_format_string(),
2636
mode=self.file_mode)
2637
return BzrDir.open(self.bzrdir.root_transport.base)
2639
def make_lock(self, name):
2640
"""Make a lock for the new control dir name."""
2641
self.step('Make %s lock' % name)
2642
ld = lockdir.LockDir(self.bzrdir.transport,
2644
file_modebits=self.file_mode,
2645
dir_modebits=self.dir_mode)
2648
def move_entry(self, new_dir, entry):
2649
"""Move then entry name into new_dir."""
2651
mandatory = entry[1]
2652
self.step('Moving %s' % name)
2654
self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
2655
except errors.NoSuchFile:
2659
def put_format(self, dirname, format):
2660
self.bzrdir.transport.put_bytes('%s/format' % dirname,
2661
format.get_format_string(),
2665
class ConvertMetaToMeta(Converter):
2666
"""Converts the components of metadirs."""
2668
def __init__(self, target_format):
2669
"""Create a metadir to metadir converter.
2671
:param target_format: The final metadir format that is desired.
2673
self.target_format = target_format
2675
def convert(self, to_convert, pb):
2676
"""See Converter.convert()."""
2677
self.bzrdir = to_convert
2681
self.step('checking repository format')
2683
repo = self.bzrdir.open_repository()
2684
except errors.NoRepositoryPresent:
2687
if not isinstance(repo._format, self.target_format.repository_format.__class__):
2688
from bzrlib.repository import CopyConverter
2689
self.pb.note('starting repository conversion')
2690
converter = CopyConverter(self.target_format.repository_format)
2691
converter.convert(repo, pb)
2693
branch = self.bzrdir.open_branch()
2694
except errors.NotBranchError:
2697
# TODO: conversions of Branch and Tree should be done by
2698
# InterXFormat lookups/some sort of registry.
2699
# Avoid circular imports
2700
from bzrlib import branch as _mod_branch
2701
old = branch._format.__class__
2702
new = self.target_format.get_branch_format().__class__
2704
if (old == _mod_branch.BzrBranchFormat5 and
2705
new in (_mod_branch.BzrBranchFormat6,
2706
_mod_branch.BzrBranchFormat7)):
2707
branch_converter = _mod_branch.Converter5to6()
2708
elif (old == _mod_branch.BzrBranchFormat6 and
2709
new == _mod_branch.BzrBranchFormat7):
2710
branch_converter = _mod_branch.Converter6to7()
2712
raise errors.BadConversionTarget("No converter", new)
2713
branch_converter.convert(branch)
2714
branch = self.bzrdir.open_branch()
2715
old = branch._format.__class__
2717
tree = self.bzrdir.open_workingtree(recommend_upgrade=False)
2718
except (errors.NoWorkingTree, errors.NotLocalUrl):
2721
# TODO: conversions of Branch and Tree should be done by
2722
# InterXFormat lookups
2723
if (isinstance(tree, workingtree.WorkingTree3) and
2724
not isinstance(tree, workingtree_4.DirStateWorkingTree) and
2725
isinstance(self.target_format.workingtree_format,
2726
workingtree_4.DirStateWorkingTreeFormat)):
2727
workingtree_4.Converter3to4().convert(tree)
2728
if (isinstance(tree, workingtree_4.DirStateWorkingTree) and
2729
not isinstance(tree, workingtree_4.WorkingTree5) and
2730
isinstance(self.target_format.workingtree_format,
2731
workingtree_4.WorkingTreeFormat5)):
2732
workingtree_4.Converter4to5().convert(tree)
2736
# This is not in remote.py because it's small, and needs to be registered.
2737
# Putting it in remote.py creates a circular import problem.
2738
# we can make it a lazy object if the control formats is turned into something
2740
class RemoteBzrDirFormat(BzrDirMetaFormat1):
2741
"""Format representing bzrdirs accessed via a smart server"""
2744
BzrDirMetaFormat1.__init__(self)
2745
self._network_name = None
2747
def get_format_description(self):
2748
return 'bzr remote bzrdir'
2750
def get_format_string(self):
2751
raise NotImplementedError(self.get_format_string)
2753
def network_name(self):
2754
if self._network_name:
2755
return self._network_name
2757
raise AssertionError("No network name set.")
2760
def probe_transport(klass, transport):
2761
"""Return a RemoteBzrDirFormat object if it looks possible."""
2763
medium = transport.get_smart_medium()
2764
except (NotImplementedError, AttributeError,
2765
errors.TransportNotPossible, errors.NoSmartMedium,
2766
errors.SmartProtocolError):
2767
# no smart server, so not a branch for this format type.
2768
raise errors.NotBranchError(path=transport.base)
2770
# Decline to open it if the server doesn't support our required
2771
# version (3) so that the VFS-based transport will do it.
2772
if medium.should_probe():
2774
server_version = medium.protocol_version()
2775
except errors.SmartProtocolError:
2776
# Apparently there's no usable smart server there, even though
2777
# the medium supports the smart protocol.
2778
raise errors.NotBranchError(path=transport.base)
2779
if server_version != '2':
2780
raise errors.NotBranchError(path=transport.base)
2783
def initialize_on_transport(self, transport):
2785
# hand off the request to the smart server
2786
client_medium = transport.get_smart_medium()
2787
except errors.NoSmartMedium:
2788
# TODO: lookup the local format from a server hint.
2789
local_dir_format = BzrDirMetaFormat1()
2790
return local_dir_format.initialize_on_transport(transport)
2791
client = _SmartClient(client_medium)
2792
path = client.remote_path_from_transport(transport)
2793
response = client.call('BzrDirFormat.initialize', path)
2794
if response[0] != 'ok':
2795
raise errors.SmartProtocolError('unexpected response code %s' % (response,))
2796
format = RemoteBzrDirFormat()
2797
self._supply_sub_formats_to(format)
2798
return remote.RemoteBzrDir(transport, format)
2800
def _open(self, transport):
2801
return remote.RemoteBzrDir(transport, self)
2803
def __eq__(self, other):
2804
if not isinstance(other, RemoteBzrDirFormat):
2806
return self.get_format_description() == other.get_format_description()
2808
def __return_repository_format(self):
2809
# Always return a RemoteRepositoryFormat object, but if a specific bzr
2810
# repository format has been asked for, tell the RemoteRepositoryFormat
2811
# that it should use that for init() etc.
2812
result = remote.RemoteRepositoryFormat()
2813
custom_format = getattr(self, '_repository_format', None)
2815
# We will use the custom format to create repositories over the
2816
# wire; expose its details like rich_root_data for code to query
2817
if isinstance(custom_format, remote.RemoteRepositoryFormat):
2818
result._custom_format = custom_format._custom_format
2820
result._custom_format = custom_format
2821
result.rich_root_data = custom_format.rich_root_data
2824
def get_branch_format(self):
2825
result = BzrDirMetaFormat1.get_branch_format(self)
2826
if not isinstance(result, remote.RemoteBranchFormat):
2827
new_result = remote.RemoteBranchFormat()
2828
new_result._custom_format = result
2830
self.set_branch_format(new_result)
2834
repository_format = property(__return_repository_format,
2835
BzrDirMetaFormat1._set_repository_format) #.im_func)
2838
BzrDirFormat.register_control_server_format(RemoteBzrDirFormat)
2841
class BzrDirFormatInfo(object):
2843
def __init__(self, native, deprecated, hidden, experimental):
2844
self.deprecated = deprecated
2845
self.native = native
2846
self.hidden = hidden
2847
self.experimental = experimental
2850
class BzrDirFormatRegistry(registry.Registry):
2851
"""Registry of user-selectable BzrDir subformats.
2853
Differs from BzrDirFormat._control_formats in that it provides sub-formats,
2854
e.g. BzrDirMeta1 with weave repository. Also, it's more user-oriented.
2858
"""Create a BzrDirFormatRegistry."""
2859
self._aliases = set()
2860
self._registration_order = list()
2861
super(BzrDirFormatRegistry, self).__init__()
2864
"""Return a set of the format names which are aliases."""
2865
return frozenset(self._aliases)
2867
def register_metadir(self, key,
2868
repository_format, help, native=True, deprecated=False,
2874
"""Register a metadir subformat.
2876
These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
2877
by the Repository/Branch/WorkingTreeformats.
2879
:param repository_format: The fully-qualified repository format class
2881
:param branch_format: Fully-qualified branch format class name as
2883
:param tree_format: Fully-qualified tree format class name as
2886
# This should be expanded to support setting WorkingTree and Branch
2887
# formats, once BzrDirMetaFormat1 supports that.
2888
def _load(full_name):
2889
mod_name, factory_name = full_name.rsplit('.', 1)
2891
mod = __import__(mod_name, globals(), locals(),
2893
except ImportError, e:
2894
raise ImportError('failed to load %s: %s' % (full_name, e))
2896
factory = getattr(mod, factory_name)
2897
except AttributeError:
2898
raise AttributeError('no factory %s in module %r'
2903
bd = BzrDirMetaFormat1()
2904
if branch_format is not None:
2905
bd.set_branch_format(_load(branch_format))
2906
if tree_format is not None:
2907
bd.workingtree_format = _load(tree_format)
2908
if repository_format is not None:
2909
bd.repository_format = _load(repository_format)
2911
self.register(key, helper, help, native, deprecated, hidden,
2912
experimental, alias)
2914
def register(self, key, factory, help, native=True, deprecated=False,
2915
hidden=False, experimental=False, alias=False):
2916
"""Register a BzrDirFormat factory.
2918
The factory must be a callable that takes one parameter: the key.
2919
It must produce an instance of the BzrDirFormat when called.
2921
This function mainly exists to prevent the info object from being
2924
registry.Registry.register(self, key, factory, help,
2925
BzrDirFormatInfo(native, deprecated, hidden, experimental))
2927
self._aliases.add(key)
2928
self._registration_order.append(key)
2930
def register_lazy(self, key, module_name, member_name, help, native=True,
2931
deprecated=False, hidden=False, experimental=False, alias=False):
2932
registry.Registry.register_lazy(self, key, module_name, member_name,
2933
help, BzrDirFormatInfo(native, deprecated, hidden, experimental))
2935
self._aliases.add(key)
2936
self._registration_order.append(key)
2938
def set_default(self, key):
2939
"""Set the 'default' key to be a clone of the supplied key.
2941
This method must be called once and only once.
2943
registry.Registry.register(self, 'default', self.get(key),
2944
self.get_help(key), info=self.get_info(key))
2945
self._aliases.add('default')
2947
def set_default_repository(self, key):
2948
"""Set the FormatRegistry default and Repository default.
2950
This is a transitional method while Repository.set_default_format
2953
if 'default' in self:
2954
self.remove('default')
2955
self.set_default(key)
2956
format = self.get('default')()
2958
def make_bzrdir(self, key):
2959
return self.get(key)()
2961
def help_topic(self, topic):
2963
default_realkey = None
2964
default_help = self.get_help('default')
2966
for key in self._registration_order:
2967
if key == 'default':
2969
help = self.get_help(key)
2970
if help == default_help:
2971
default_realkey = key
2973
help_pairs.append((key, help))
2975
def wrapped(key, help, info):
2977
help = '(native) ' + help
2978
return ':%s:\n%s\n\n' % (key,
2979
textwrap.fill(help, initial_indent=' ',
2980
subsequent_indent=' '))
2981
if default_realkey is not None:
2982
output += wrapped(default_realkey, '(default) %s' % default_help,
2983
self.get_info('default'))
2984
deprecated_pairs = []
2985
experimental_pairs = []
2986
for key, help in help_pairs:
2987
info = self.get_info(key)
2990
elif info.deprecated:
2991
deprecated_pairs.append((key, help))
2992
elif info.experimental:
2993
experimental_pairs.append((key, help))
2995
output += wrapped(key, help, info)
2996
output += "\nSee ``bzr help formats`` for more about storage formats."
2998
if len(experimental_pairs) > 0:
2999
other_output += "Experimental formats are shown below.\n\n"
3000
for key, help in experimental_pairs:
3001
info = self.get_info(key)
3002
other_output += wrapped(key, help, info)
3005
"No experimental formats are available.\n\n"
3006
if len(deprecated_pairs) > 0:
3007
other_output += "\nDeprecated formats are shown below.\n\n"
3008
for key, help in deprecated_pairs:
3009
info = self.get_info(key)
3010
other_output += wrapped(key, help, info)
3013
"\nNo deprecated formats are available.\n\n"
3015
"\nSee ``bzr help formats`` for more about storage formats."
3017
if topic == 'other-formats':
3023
class RepositoryAcquisitionPolicy(object):
3024
"""Abstract base class for repository acquisition policies.
3026
A repository acquisition policy decides how a BzrDir acquires a repository
3027
for a branch that is being created. The most basic policy decision is
3028
whether to create a new repository or use an existing one.
3030
def __init__(self, stack_on, stack_on_pwd, require_stacking):
3033
:param stack_on: A location to stack on
3034
:param stack_on_pwd: If stack_on is relative, the location it is
3036
:param require_stacking: If True, it is a failure to not stack.
3038
self._stack_on = stack_on
3039
self._stack_on_pwd = stack_on_pwd
3040
self._require_stacking = require_stacking
3042
def configure_branch(self, branch):
3043
"""Apply any configuration data from this policy to the branch.
3045
Default implementation sets repository stacking.
3047
if self._stack_on is None:
3049
if self._stack_on_pwd is None:
3050
stack_on = self._stack_on
3053
stack_on = urlutils.rebase_url(self._stack_on,
3055
branch.bzrdir.root_transport.base)
3056
except errors.InvalidRebaseURLs:
3057
stack_on = self._get_full_stack_on()
3059
branch.set_stacked_on_url(stack_on)
3060
except errors.UnstackableBranchFormat:
3061
if self._require_stacking:
3064
def _get_full_stack_on(self):
3065
"""Get a fully-qualified URL for the stack_on location."""
3066
if self._stack_on is None:
3068
if self._stack_on_pwd is None:
3069
return self._stack_on
3071
return urlutils.join(self._stack_on_pwd, self._stack_on)
3073
def _add_fallback(self, repository, possible_transports=None):
3074
"""Add a fallback to the supplied repository, if stacking is set."""
3075
stack_on = self._get_full_stack_on()
3076
if stack_on is None:
3078
stacked_dir = BzrDir.open(stack_on,
3079
possible_transports=possible_transports)
3081
stacked_repo = stacked_dir.open_branch().repository
3082
except errors.NotBranchError:
3083
stacked_repo = stacked_dir.open_repository()
3085
repository.add_fallback_repository(stacked_repo)
3086
except errors.UnstackableRepositoryFormat:
3087
if self._require_stacking:
3090
self._require_stacking = True
3092
def acquire_repository(self, make_working_trees=None, shared=False):
3093
"""Acquire a repository for this bzrdir.
3095
Implementations may create a new repository or use a pre-exising
3097
:param make_working_trees: If creating a repository, set
3098
make_working_trees to this value (if non-None)
3099
:param shared: If creating a repository, make it shared if True
3100
:return: A repository
3102
raise NotImplemented(RepositoryAcquisitionPolicy.acquire_repository)
3105
class CreateRepository(RepositoryAcquisitionPolicy):
3106
"""A policy of creating a new repository"""
3108
def __init__(self, bzrdir, stack_on=None, stack_on_pwd=None,
3109
require_stacking=False):
3112
:param bzrdir: The bzrdir to create the repository on.
3113
:param stack_on: A location to stack on
3114
:param stack_on_pwd: If stack_on is relative, the location it is
3117
RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
3119
self._bzrdir = bzrdir
3121
def acquire_repository(self, make_working_trees=None, shared=False):
3122
"""Implementation of RepositoryAcquisitionPolicy.acquire_repository
3124
Creates the desired repository in the bzrdir we already have.
3126
repository = self._bzrdir.create_repository(shared=shared)
3127
self._add_fallback(repository,
3128
possible_transports=[self._bzrdir.transport])
3129
if make_working_trees is not None:
3130
repository.set_make_working_trees(make_working_trees)
3134
class UseExistingRepository(RepositoryAcquisitionPolicy):
3135
"""A policy of reusing an existing repository"""
3137
def __init__(self, repository, stack_on=None, stack_on_pwd=None,
3138
require_stacking=False):
3141
:param repository: The repository to use.
3142
:param stack_on: A location to stack on
3143
:param stack_on_pwd: If stack_on is relative, the location it is
3146
RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
3148
self._repository = repository
3150
def acquire_repository(self, make_working_trees=None, shared=False):
3151
"""Implementation of RepositoryAcquisitionPolicy.acquire_repository
3153
Returns an existing repository to use
3155
self._add_fallback(self._repository,
3156
possible_transports=[self._repository.bzrdir.transport])
3157
return self._repository
3160
# Please register new formats after old formats so that formats
3161
# appear in chronological order and format descriptions can build
3163
format_registry = BzrDirFormatRegistry()
3164
# The pre-0.8 formats have their repository format network name registered in
3165
# repository.py. MetaDir formats have their repository format network name
3166
# inferred from their disk format string.
3167
format_registry.register('weave', BzrDirFormat6,
3168
'Pre-0.8 format. Slower than knit and does not'
3169
' support checkouts or shared repositories.',
3171
format_registry.register_metadir('metaweave',
3172
'bzrlib.repofmt.weaverepo.RepositoryFormat7',
3173
'Transitional format in 0.8. Slower than knit.',
3174
branch_format='bzrlib.branch.BzrBranchFormat5',
3175
tree_format='bzrlib.workingtree.WorkingTreeFormat3',
3177
format_registry.register_metadir('knit',
3178
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3179
'Format using knits. Recommended for interoperation with bzr <= 0.14.',
3180
branch_format='bzrlib.branch.BzrBranchFormat5',
3181
tree_format='bzrlib.workingtree.WorkingTreeFormat3',
3183
format_registry.register_metadir('dirstate',
3184
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3185
help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
3186
'above when accessed over the network.',
3187
branch_format='bzrlib.branch.BzrBranchFormat5',
3188
# this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
3189
# directly from workingtree_4 triggers a circular import.
3190
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3192
format_registry.register_metadir('dirstate-tags',
3193
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3194
help='New in 0.15: Fast local operations and improved scaling for '
3195
'network operations. Additionally adds support for tags.'
3196
' Incompatible with bzr < 0.15.',
3197
branch_format='bzrlib.branch.BzrBranchFormat6',
3198
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3200
format_registry.register_metadir('rich-root',
3201
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
3202
help='New in 1.0. Better handling of tree roots. Incompatible with'
3204
branch_format='bzrlib.branch.BzrBranchFormat6',
3205
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3207
format_registry.register_metadir('dirstate-with-subtree',
3208
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
3209
help='New in 0.15: Fast local operations and improved scaling for '
3210
'network operations. Additionally adds support for versioning nested '
3211
'bzr branches. Incompatible with bzr < 0.15.',
3212
branch_format='bzrlib.branch.BzrBranchFormat6',
3213
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3217
format_registry.register_metadir('pack-0.92',
3218
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
3219
help='New in 0.92: Pack-based format with data compatible with '
3220
'dirstate-tags format repositories. Interoperates with '
3221
'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
3222
'Previously called knitpack-experimental. '
3223
'For more information, see '
3224
'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
3225
branch_format='bzrlib.branch.BzrBranchFormat6',
3226
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3228
format_registry.register_metadir('pack-0.92-subtree',
3229
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
3230
help='New in 0.92: Pack-based format with data compatible with '
3231
'dirstate-with-subtree format repositories. Interoperates with '
3232
'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
3233
'Previously called knitpack-experimental. '
3234
'For more information, see '
3235
'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
3236
branch_format='bzrlib.branch.BzrBranchFormat6',
3237
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3241
format_registry.register_metadir('rich-root-pack',
3242
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
3243
help='New in 1.0: A variant of pack-0.92 that supports rich-root data '
3244
'(needed for bzr-svn).',
3245
branch_format='bzrlib.branch.BzrBranchFormat6',
3246
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3248
format_registry.register_metadir('1.6',
3249
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5',
3250
help='A format that allows a branch to indicate that there is another '
3251
'(stacked) repository that should be used to access data that is '
3252
'not present locally.',
3253
branch_format='bzrlib.branch.BzrBranchFormat7',
3254
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3256
format_registry.register_metadir('1.6.1-rich-root',
3257
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5RichRoot',
3258
help='A variant of 1.6 that supports rich-root data '
3259
'(needed for bzr-svn).',
3260
branch_format='bzrlib.branch.BzrBranchFormat7',
3261
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3263
format_registry.register_metadir('1.9',
3264
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
3265
help='A repository format using B+tree indexes. These indexes '
3266
'are smaller in size, have smarter caching and provide faster '
3267
'performance for most operations.',
3268
branch_format='bzrlib.branch.BzrBranchFormat7',
3269
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3271
format_registry.register_metadir('1.9-rich-root',
3272
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
3273
help='A variant of 1.9 that supports rich-root data '
3274
'(needed for bzr-svn).',
3275
branch_format='bzrlib.branch.BzrBranchFormat7',
3276
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3278
format_registry.register_metadir('development-wt5',
3279
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
3280
help='A working-tree format that supports views and content filtering.',
3281
branch_format='bzrlib.branch.BzrBranchFormat7',
3282
tree_format='bzrlib.workingtree.WorkingTreeFormat5',
3285
format_registry.register_metadir('development-wt5-rich-root',
3286
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
3287
help='A variant of development-wt5 that supports rich-root data '
3288
'(needed for bzr-svn).',
3289
branch_format='bzrlib.branch.BzrBranchFormat7',
3290
tree_format='bzrlib.workingtree.WorkingTreeFormat5',
3293
# The following two formats should always just be aliases.
3294
format_registry.register_metadir('development',
3295
'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2',
3296
help='Current development format. Can convert data to and from pack-0.92 '
3297
'(and anything compatible with pack-0.92) format repositories. '
3298
'Repositories and branches in this format can only be read by bzr.dev. '
3300
'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3302
branch_format='bzrlib.branch.BzrBranchFormat7',
3303
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3307
format_registry.register_metadir('development-subtree',
3308
'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
3309
help='Current development format, subtree variant. Can convert data to and '
3310
'from pack-0.92-subtree (and anything compatible with '
3311
'pack-0.92-subtree) format repositories. Repositories and branches in '
3312
'this format can only be read by bzr.dev. Please read '
3313
'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3315
branch_format='bzrlib.branch.BzrBranchFormat7',
3316
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3320
# And the development formats above will have aliased one of the following:
3321
format_registry.register_metadir('development2',
3322
'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2',
3323
help='1.6.1 with B+Tree based index. '
3325
'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3327
branch_format='bzrlib.branch.BzrBranchFormat7',
3328
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3332
format_registry.register_metadir('development2-subtree',
3333
'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
3334
help='1.6.1-subtree with B+Tree based index. '
3336
'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3338
branch_format='bzrlib.branch.BzrBranchFormat7',
3339
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3343
# The current format that is made on 'bzr init'.
3344
format_registry.set_default('pack-0.92')