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, is_new_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
if is_new_repo and not require_stacking and revision_id is not None:
226
fetch_spec = graph.PendingAncestryResult(
227
[revision_id], local_repo)
228
result_repo.fetch(local_repo, fetch_spec=fetch_spec)
230
result_repo.fetch(local_repo, revision_id=revision_id)
233
# 1 if there is a branch present
234
# make sure its content is available in the target repository
236
if local_branch is not None:
237
result_branch = local_branch.clone(result, revision_id=revision_id,
238
repository_policy=repository_policy)
240
# Cheaper to check if the target is not local, than to try making
242
result.root_transport.local_abspath('.')
243
if result_repo is None or result_repo.make_working_trees():
244
self.open_workingtree().clone(result)
245
except (errors.NoWorkingTree, errors.NotLocalUrl):
249
# TODO: This should be given a Transport, and should chdir up; otherwise
250
# this will open a new connection.
251
def _make_tail(self, url):
252
t = get_transport(url)
256
def create(cls, base, format=None, possible_transports=None):
257
"""Create a new BzrDir at the url 'base'.
259
:param format: If supplied, the format of branch to create. If not
260
supplied, the default is used.
261
:param possible_transports: If supplied, a list of transports that
262
can be reused to share a remote connection.
264
if cls is not BzrDir:
265
raise AssertionError("BzrDir.create always creates the default"
266
" format, not one of %r" % cls)
267
t = get_transport(base, possible_transports)
270
format = BzrDirFormat.get_default_format()
271
return format.initialize_on_transport(t)
274
def find_bzrdirs(transport, evaluate=None, list_current=None):
275
"""Find bzrdirs recursively from current location.
277
This is intended primarily as a building block for more sophisticated
278
functionality, like finding trees under a directory, or finding
279
branches that use a given repository.
280
:param evaluate: An optional callable that yields recurse, value,
281
where recurse controls whether this bzrdir is recursed into
282
and value is the value to yield. By default, all bzrdirs
283
are recursed into, and the return value is the bzrdir.
284
:param list_current: if supplied, use this function to list the current
285
directory, instead of Transport.list_dir
286
:return: a generator of found bzrdirs, or whatever evaluate returns.
288
if list_current is None:
289
def list_current(transport):
290
return transport.list_dir('')
292
def evaluate(bzrdir):
295
pending = [transport]
296
while len(pending) > 0:
297
current_transport = pending.pop()
300
bzrdir = BzrDir.open_from_transport(current_transport)
301
except errors.NotBranchError:
304
recurse, value = evaluate(bzrdir)
307
subdirs = list_current(current_transport)
308
except errors.NoSuchFile:
311
for subdir in sorted(subdirs, reverse=True):
312
pending.append(current_transport.clone(subdir))
315
def find_branches(transport):
316
"""Find all branches under a transport.
318
This will find all branches below the transport, including branches
319
inside other branches. Where possible, it will use
320
Repository.find_branches.
322
To list all the branches that use a particular Repository, see
323
Repository.find_branches
325
def evaluate(bzrdir):
327
repository = bzrdir.open_repository()
328
except errors.NoRepositoryPresent:
331
return False, (None, repository)
333
branch = bzrdir.open_branch()
334
except errors.NotBranchError:
335
return True, (None, None)
337
return True, (branch, None)
339
for branch, repo in BzrDir.find_bzrdirs(transport, evaluate=evaluate):
341
branches.extend(repo.find_branches())
342
if branch is not None:
343
branches.append(branch)
346
def destroy_repository(self):
347
"""Destroy the repository in this BzrDir"""
348
raise NotImplementedError(self.destroy_repository)
350
def create_branch(self):
351
"""Create a branch in this BzrDir.
353
The bzrdir's format will control what branch format is created.
354
For more control see BranchFormatXX.create(a_bzrdir).
356
raise NotImplementedError(self.create_branch)
358
def destroy_branch(self):
359
"""Destroy the branch in this BzrDir"""
360
raise NotImplementedError(self.destroy_branch)
363
def create_branch_and_repo(base, force_new_repo=False, format=None):
364
"""Create a new BzrDir, Branch and Repository at the url 'base'.
366
This will use the current default BzrDirFormat unless one is
367
specified, and use whatever
368
repository format that that uses via bzrdir.create_branch and
369
create_repository. If a shared repository is available that is used
372
The created Branch object is returned.
374
:param base: The URL to create the branch at.
375
:param force_new_repo: If True a new repository is always created.
376
:param format: If supplied, the format of branch to create. If not
377
supplied, the default is used.
379
bzrdir = BzrDir.create(base, format)
380
bzrdir._find_or_create_repository(force_new_repo)
381
return bzrdir.create_branch()
383
def determine_repository_policy(self, force_new_repo=False, stack_on=None,
384
stack_on_pwd=None, require_stacking=False):
385
"""Return an object representing a policy to use.
387
This controls whether a new repository is created, or a shared
388
repository used instead.
390
If stack_on is supplied, will not seek a containing shared repo.
392
:param force_new_repo: If True, require a new repository to be created.
393
:param stack_on: If supplied, the location to stack on. If not
394
supplied, a default_stack_on location may be used.
395
:param stack_on_pwd: If stack_on is relative, the location it is
398
def repository_policy(found_bzrdir):
401
config = found_bzrdir.get_config()
403
if config is not None:
404
stack_on = config.get_default_stack_on()
405
if stack_on is not None:
406
stack_on_pwd = found_bzrdir.root_transport.base
408
note('Using default stacking branch %s at %s', stack_on,
410
# does it have a repository ?
412
repository = found_bzrdir.open_repository()
413
except errors.NoRepositoryPresent:
416
if ((found_bzrdir.root_transport.base !=
417
self.root_transport.base) and not repository.is_shared()):
424
return UseExistingRepository(repository, stack_on,
425
stack_on_pwd, require_stacking=require_stacking), True
427
return CreateRepository(self, stack_on, stack_on_pwd,
428
require_stacking=require_stacking), True
430
if not force_new_repo:
432
policy = self._find_containing(repository_policy)
433
if policy is not None:
437
return UseExistingRepository(self.open_repository(),
438
stack_on, stack_on_pwd,
439
require_stacking=require_stacking)
440
except errors.NoRepositoryPresent:
442
return CreateRepository(self, stack_on, stack_on_pwd,
443
require_stacking=require_stacking)
445
def _find_or_create_repository(self, force_new_repo):
446
"""Create a new repository if needed, returning the repository."""
447
policy = self.determine_repository_policy(force_new_repo)
448
return policy.acquire_repository()[0]
451
def create_branch_convenience(base, force_new_repo=False,
452
force_new_tree=None, format=None,
453
possible_transports=None):
454
"""Create a new BzrDir, Branch and Repository at the url 'base'.
456
This is a convenience function - it will use an existing repository
457
if possible, can be told explicitly whether to create a working tree or
460
This will use the current default BzrDirFormat unless one is
461
specified, and use whatever
462
repository format that that uses via bzrdir.create_branch and
463
create_repository. If a shared repository is available that is used
464
preferentially. Whatever repository is used, its tree creation policy
467
The created Branch object is returned.
468
If a working tree cannot be made due to base not being a file:// url,
469
no error is raised unless force_new_tree is True, in which case no
470
data is created on disk and NotLocalUrl is raised.
472
:param base: The URL to create the branch at.
473
:param force_new_repo: If True a new repository is always created.
474
:param force_new_tree: If True or False force creation of a tree or
475
prevent such creation respectively.
476
:param format: Override for the bzrdir format to create.
477
:param possible_transports: An optional reusable transports list.
480
# check for non local urls
481
t = get_transport(base, possible_transports)
482
if not isinstance(t, local.LocalTransport):
483
raise errors.NotLocalUrl(base)
484
bzrdir = BzrDir.create(base, format, possible_transports)
485
repo = bzrdir._find_or_create_repository(force_new_repo)
486
result = bzrdir.create_branch()
487
if force_new_tree or (repo.make_working_trees() and
488
force_new_tree is None):
490
bzrdir.create_workingtree()
491
except errors.NotLocalUrl:
496
def create_standalone_workingtree(base, format=None):
497
"""Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
499
'base' must be a local path or a file:// url.
501
This will use the current default BzrDirFormat unless one is
502
specified, and use whatever
503
repository format that that uses for bzrdirformat.create_workingtree,
504
create_branch and create_repository.
506
:param format: Override for the bzrdir format to create.
507
:return: The WorkingTree object.
509
t = get_transport(base)
510
if not isinstance(t, local.LocalTransport):
511
raise errors.NotLocalUrl(base)
512
bzrdir = BzrDir.create_branch_and_repo(base,
514
format=format).bzrdir
515
return bzrdir.create_workingtree()
517
def create_workingtree(self, revision_id=None, from_branch=None,
518
accelerator_tree=None, hardlink=False):
519
"""Create a working tree at this BzrDir.
521
:param revision_id: create it as of this revision id.
522
:param from_branch: override bzrdir branch (for lightweight checkouts)
523
:param accelerator_tree: A tree which can be used for retrieving file
524
contents more quickly than the revision tree, i.e. a workingtree.
525
The revision tree will be used for cases where accelerator_tree's
526
content is different.
528
raise NotImplementedError(self.create_workingtree)
530
def backup_bzrdir(self):
531
"""Backup this bzr control directory.
533
:return: Tuple with old path name and new path name
535
pb = ui.ui_factory.nested_progress_bar()
537
# FIXME: bug 300001 -- the backup fails if the backup directory
538
# already exists, but it should instead either remove it or make
539
# a new backup directory.
541
# FIXME: bug 262450 -- the backup directory should have the same
542
# permissions as the .bzr directory (probably a bug in copy_tree)
543
old_path = self.root_transport.abspath('.bzr')
544
new_path = self.root_transport.abspath('backup.bzr')
545
pb.note('making backup of %s' % (old_path,))
546
pb.note(' to %s' % (new_path,))
547
self.root_transport.copy_tree('.bzr', 'backup.bzr')
548
return (old_path, new_path)
552
def retire_bzrdir(self, limit=10000):
553
"""Permanently disable the bzrdir.
555
This is done by renaming it to give the user some ability to recover
556
if there was a problem.
558
This will have horrible consequences if anyone has anything locked or
560
:param limit: number of times to retry
565
to_path = '.bzr.retired.%d' % i
566
self.root_transport.rename('.bzr', to_path)
567
note("renamed %s to %s"
568
% (self.root_transport.abspath('.bzr'), to_path))
570
except (errors.TransportError, IOError, errors.PathError):
577
def destroy_workingtree(self):
578
"""Destroy the working tree at this BzrDir.
580
Formats that do not support this may raise UnsupportedOperation.
582
raise NotImplementedError(self.destroy_workingtree)
584
def destroy_workingtree_metadata(self):
585
"""Destroy the control files for the working tree at this BzrDir.
587
The contents of working tree files are not affected.
588
Formats that do not support this may raise UnsupportedOperation.
590
raise NotImplementedError(self.destroy_workingtree_metadata)
592
def _find_containing(self, evaluate):
593
"""Find something in a containing control directory.
595
This method will scan containing control dirs, until it finds what
596
it is looking for, decides that it will never find it, or runs out
597
of containing control directories to check.
599
It is used to implement find_repository and
600
determine_repository_policy.
602
:param evaluate: A function returning (value, stop). If stop is True,
603
the value will be returned.
607
result, stop = evaluate(found_bzrdir)
610
next_transport = found_bzrdir.root_transport.clone('..')
611
if (found_bzrdir.root_transport.base == next_transport.base):
612
# top of the file system
614
# find the next containing bzrdir
616
found_bzrdir = BzrDir.open_containing_from_transport(
618
except errors.NotBranchError:
621
def find_repository(self):
622
"""Find the repository that should be used.
624
This does not require a branch as we use it to find the repo for
625
new branches as well as to hook existing branches up to their
628
def usable_repository(found_bzrdir):
629
# does it have a repository ?
631
repository = found_bzrdir.open_repository()
632
except errors.NoRepositoryPresent:
634
if found_bzrdir.root_transport.base == self.root_transport.base:
635
return repository, True
636
elif repository.is_shared():
637
return repository, True
641
found_repo = self._find_containing(usable_repository)
642
if found_repo is None:
643
raise errors.NoRepositoryPresent(self)
646
def get_branch_reference(self):
647
"""Return the referenced URL for the branch in this bzrdir.
649
:raises NotBranchError: If there is no Branch.
650
:return: The URL the branch in this bzrdir references if it is a
651
reference branch, or None for regular branches.
655
def get_branch_transport(self, branch_format):
656
"""Get the transport for use by branch format in this BzrDir.
658
Note that bzr dirs that do not support format strings will raise
659
IncompatibleFormat if the branch format they are given has
660
a format string, and vice versa.
662
If branch_format is None, the transport is returned with no
663
checking. If it is not None, then the returned transport is
664
guaranteed to point to an existing directory ready for use.
666
raise NotImplementedError(self.get_branch_transport)
668
def _find_creation_modes(self):
669
"""Determine the appropriate modes for files and directories.
671
They're always set to be consistent with the base directory,
672
assuming that this transport allows setting modes.
674
# TODO: Do we need or want an option (maybe a config setting) to turn
675
# this off or override it for particular locations? -- mbp 20080512
676
if self._mode_check_done:
678
self._mode_check_done = True
680
st = self.transport.stat('.')
681
except errors.TransportNotPossible:
682
self._dir_mode = None
683
self._file_mode = None
685
# Check the directory mode, but also make sure the created
686
# directories and files are read-write for this user. This is
687
# mostly a workaround for filesystems which lie about being able to
688
# write to a directory (cygwin & win32)
689
if (st.st_mode & 07777 == 00000):
690
# FTP allows stat but does not return dir/file modes
691
self._dir_mode = None
692
self._file_mode = None
694
self._dir_mode = (st.st_mode & 07777) | 00700
695
# Remove the sticky and execute bits for files
696
self._file_mode = self._dir_mode & ~07111
698
def _get_file_mode(self):
699
"""Return Unix mode for newly created files, or None.
701
if not self._mode_check_done:
702
self._find_creation_modes()
703
return self._file_mode
705
def _get_dir_mode(self):
706
"""Return Unix mode for newly created directories, or None.
708
if not self._mode_check_done:
709
self._find_creation_modes()
710
return self._dir_mode
712
def get_repository_transport(self, repository_format):
713
"""Get the transport for use by repository format in this BzrDir.
715
Note that bzr dirs that do not support format strings will raise
716
IncompatibleFormat if the repository format they are given has
717
a format string, and vice versa.
719
If repository_format is None, the transport is returned with no
720
checking. If it is not None, then the returned transport is
721
guaranteed to point to an existing directory ready for use.
723
raise NotImplementedError(self.get_repository_transport)
725
def get_workingtree_transport(self, tree_format):
726
"""Get the transport for use by workingtree format in this BzrDir.
728
Note that bzr dirs that do not support format strings will raise
729
IncompatibleFormat if the workingtree format they are given has a
730
format string, and vice versa.
732
If workingtree_format is None, the transport is returned with no
733
checking. If it is not None, then the returned transport is
734
guaranteed to point to an existing directory ready for use.
736
raise NotImplementedError(self.get_workingtree_transport)
738
def get_config(self):
739
if getattr(self, '_get_config', None) is None:
741
return self._get_config()
743
def __init__(self, _transport, _format):
744
"""Initialize a Bzr control dir object.
746
Only really common logic should reside here, concrete classes should be
747
made with varying behaviours.
749
:param _format: the format that is creating this BzrDir instance.
750
:param _transport: the transport this dir is based at.
752
self._format = _format
753
self.transport = _transport.clone('.bzr')
754
self.root_transport = _transport
755
self._mode_check_done = False
757
def is_control_filename(self, filename):
758
"""True if filename is the name of a path which is reserved for bzrdir's.
760
:param filename: A filename within the root transport of this bzrdir.
762
This is true IF and ONLY IF the filename is part of the namespace reserved
763
for bzr control dirs. Currently this is the '.bzr' directory in the root
764
of the root_transport. it is expected that plugins will need to extend
765
this in the future - for instance to make bzr talk with svn working
768
# this might be better on the BzrDirFormat class because it refers to
769
# all the possible bzrdir disk formats.
770
# This method is tested via the workingtree is_control_filename tests-
771
# it was extracted from WorkingTree.is_control_filename. If the method's
772
# contract is extended beyond the current trivial implementation, please
773
# add new tests for it to the appropriate place.
774
return filename == '.bzr' or filename.startswith('.bzr/')
776
def needs_format_conversion(self, format=None):
777
"""Return true if this bzrdir needs convert_format run on it.
779
For instance, if the repository format is out of date but the
780
branch and working tree are not, this should return True.
782
:param format: Optional parameter indicating a specific desired
783
format we plan to arrive at.
785
raise NotImplementedError(self.needs_format_conversion)
788
def open_unsupported(base):
789
"""Open a branch which is not supported."""
790
return BzrDir.open(base, _unsupported=True)
793
def open(base, _unsupported=False, possible_transports=None):
794
"""Open an existing bzrdir, rooted at 'base' (url).
796
:param _unsupported: a private parameter to the BzrDir class.
798
t = get_transport(base, possible_transports=possible_transports)
799
return BzrDir.open_from_transport(t, _unsupported=_unsupported)
802
def open_from_transport(transport, _unsupported=False,
803
_server_formats=True):
804
"""Open a bzrdir within a particular directory.
806
:param transport: Transport containing the bzrdir.
807
:param _unsupported: private.
809
# Keep initial base since 'transport' may be modified while following
811
base = transport.base
812
def find_format(transport):
813
return transport, BzrDirFormat.find_format(
814
transport, _server_formats=_server_formats)
816
def redirected(transport, e, redirection_notice):
817
redirected_transport = transport._redirected_to(e.source, e.target)
818
if redirected_transport is None:
819
raise errors.NotBranchError(base)
820
note('%s is%s redirected to %s',
821
transport.base, e.permanently, redirected_transport.base)
822
return redirected_transport
825
transport, format = do_catching_redirections(find_format,
828
except errors.TooManyRedirections:
829
raise errors.NotBranchError(base)
831
BzrDir._check_supported(format, _unsupported)
832
return format.open(transport, _found=True)
834
def open_branch(self, unsupported=False):
835
"""Open the branch object at this BzrDir if one is present.
837
If unsupported is True, then no longer supported branch formats can
840
TODO: static convenience version of this?
842
raise NotImplementedError(self.open_branch)
845
def open_containing(url, possible_transports=None):
846
"""Open an existing branch which contains url.
848
:param url: url to search from.
849
See open_containing_from_transport for more detail.
851
transport = get_transport(url, possible_transports)
852
return BzrDir.open_containing_from_transport(transport)
855
def open_containing_from_transport(a_transport):
856
"""Open an existing branch which contains a_transport.base.
858
This probes for a branch at a_transport, and searches upwards from there.
860
Basically we keep looking up until we find the control directory or
861
run into the root. If there isn't one, raises NotBranchError.
862
If there is one and it is either an unrecognised format or an unsupported
863
format, UnknownFormatError or UnsupportedFormatError are raised.
864
If there is one, it is returned, along with the unused portion of url.
866
:return: The BzrDir that contains the path, and a Unicode path
867
for the rest of the URL.
869
# this gets the normalised url back. I.e. '.' -> the full path.
870
url = a_transport.base
873
result = BzrDir.open_from_transport(a_transport)
874
return result, urlutils.unescape(a_transport.relpath(url))
875
except errors.NotBranchError, e:
878
new_t = a_transport.clone('..')
879
except errors.InvalidURLJoin:
880
# reached the root, whatever that may be
881
raise errors.NotBranchError(path=url)
882
if new_t.base == a_transport.base:
883
# reached the root, whatever that may be
884
raise errors.NotBranchError(path=url)
887
def _get_tree_branch(self):
888
"""Return the branch and tree, if any, for this bzrdir.
890
Return None for tree if not present or inaccessible.
891
Raise NotBranchError if no branch is present.
892
:return: (tree, branch)
895
tree = self.open_workingtree()
896
except (errors.NoWorkingTree, errors.NotLocalUrl):
898
branch = self.open_branch()
904
def open_tree_or_branch(klass, location):
905
"""Return the branch and working tree at a location.
907
If there is no tree at the location, tree will be None.
908
If there is no branch at the location, an exception will be
910
:return: (tree, branch)
912
bzrdir = klass.open(location)
913
return bzrdir._get_tree_branch()
916
def open_containing_tree_or_branch(klass, location):
917
"""Return the branch and working tree contained by a location.
919
Returns (tree, branch, relpath).
920
If there is no tree at containing the location, tree will be None.
921
If there is no branch containing the location, an exception will be
923
relpath is the portion of the path that is contained by the branch.
925
bzrdir, relpath = klass.open_containing(location)
926
tree, branch = bzrdir._get_tree_branch()
927
return tree, branch, relpath
930
def open_containing_tree_branch_or_repository(klass, location):
931
"""Return the working tree, branch and repo contained by a location.
933
Returns (tree, branch, repository, relpath).
934
If there is no tree containing the location, tree will be None.
935
If there is no branch containing the location, branch will be None.
936
If there is no repository containing the location, repository will be
938
relpath is the portion of the path that is contained by the innermost
941
If no tree, branch or repository is found, a NotBranchError is raised.
943
bzrdir, relpath = klass.open_containing(location)
945
tree, branch = bzrdir._get_tree_branch()
946
except errors.NotBranchError:
948
repo = bzrdir.find_repository()
949
return None, None, repo, relpath
950
except (errors.NoRepositoryPresent):
951
raise errors.NotBranchError(location)
952
return tree, branch, branch.repository, relpath
954
def open_repository(self, _unsupported=False):
955
"""Open the repository object at this BzrDir if one is present.
957
This will not follow the Branch object pointer - it's strictly a direct
958
open facility. Most client code should use open_branch().repository to
961
:param _unsupported: a private parameter, not part of the api.
962
TODO: static convenience version of this?
964
raise NotImplementedError(self.open_repository)
966
def open_workingtree(self, _unsupported=False,
967
recommend_upgrade=True, from_branch=None):
968
"""Open the workingtree object at this BzrDir if one is present.
970
:param recommend_upgrade: Optional keyword parameter, when True (the
971
default), emit through the ui module a recommendation that the user
972
upgrade the working tree when the workingtree being opened is old
973
(but still fully supported).
974
:param from_branch: override bzrdir branch (for lightweight checkouts)
976
raise NotImplementedError(self.open_workingtree)
978
def has_branch(self):
979
"""Tell if this bzrdir contains a branch.
981
Note: if you're going to open the branch, you should just go ahead
982
and try, and not ask permission first. (This method just opens the
983
branch and discards it, and that's somewhat expensive.)
988
except errors.NotBranchError:
991
def has_workingtree(self):
992
"""Tell if this bzrdir contains a working tree.
994
This will still raise an exception if the bzrdir has a workingtree that
995
is remote & inaccessible.
997
Note: if you're going to open the working tree, you should just go ahead
998
and try, and not ask permission first. (This method just opens the
999
workingtree and discards it, and that's somewhat expensive.)
1002
self.open_workingtree(recommend_upgrade=False)
1004
except errors.NoWorkingTree:
1007
def _cloning_metadir(self):
1008
"""Produce a metadir suitable for cloning with.
1010
:returns: (destination_bzrdir_format, source_repository)
1012
result_format = self._format.__class__()
1015
branch = self.open_branch()
1016
source_repository = branch.repository
1017
result_format._branch_format = branch._format
1018
except errors.NotBranchError:
1019
source_branch = None
1020
source_repository = self.open_repository()
1021
except errors.NoRepositoryPresent:
1022
source_repository = None
1024
# XXX TODO: This isinstance is here because we have not implemented
1025
# the fix recommended in bug # 103195 - to delegate this choice the
1026
# repository itself.
1027
repo_format = source_repository._format
1028
if isinstance(repo_format, remote.RemoteRepositoryFormat):
1029
source_repository._ensure_real()
1030
repo_format = source_repository._real_repository._format
1031
result_format.repository_format = repo_format
1033
# TODO: Couldn't we just probe for the format in these cases,
1034
# rather than opening the whole tree? It would be a little
1035
# faster. mbp 20070401
1036
tree = self.open_workingtree(recommend_upgrade=False)
1037
except (errors.NoWorkingTree, errors.NotLocalUrl):
1038
result_format.workingtree_format = None
1040
result_format.workingtree_format = tree._format.__class__()
1041
return result_format, source_repository
1043
def cloning_metadir(self, require_stacking=False):
1044
"""Produce a metadir suitable for cloning or sprouting with.
1046
These operations may produce workingtrees (yes, even though they're
1047
"cloning" something that doesn't have a tree), so a viable workingtree
1048
format must be selected.
1050
:require_stacking: If True, non-stackable formats will be upgraded
1051
to similar stackable formats.
1052
:returns: a BzrDirFormat with all component formats either set
1053
appropriately or set to None if that component should not be
1056
format, repository = self._cloning_metadir()
1057
if format._workingtree_format is None:
1058
if repository is None:
1060
tree_format = repository._format._matchingbzrdir.workingtree_format
1061
format.workingtree_format = tree_format.__class__()
1062
if require_stacking:
1063
format.require_stacking()
1066
def checkout_metadir(self):
1067
return self.cloning_metadir()
1069
def sprout(self, url, revision_id=None, force_new_repo=False,
1070
recurse='down', possible_transports=None,
1071
accelerator_tree=None, hardlink=False, stacked=False,
1072
source_branch=None, create_tree_if_local=True):
1073
"""Create a copy of this bzrdir prepared for use as a new line of
1076
If url's last component does not exist, it will be created.
1078
Attributes related to the identity of the source branch like
1079
branch nickname will be cleaned, a working tree is created
1080
whether one existed before or not; and a local branch is always
1083
if revision_id is not None, then the clone operation may tune
1084
itself to download less data.
1085
:param accelerator_tree: A tree which can be used for retrieving file
1086
contents more quickly than the revision tree, i.e. a workingtree.
1087
The revision tree will be used for cases where accelerator_tree's
1088
content is different.
1089
:param hardlink: If true, hard-link files from accelerator_tree,
1091
:param stacked: If true, create a stacked branch referring to the
1092
location of this control directory.
1093
:param create_tree_if_local: If true, a working-tree will be created
1094
when working locally.
1096
target_transport = get_transport(url, possible_transports)
1097
target_transport.ensure_base()
1098
cloning_format = self.cloning_metadir(stacked)
1099
# Create/update the result branch
1100
result = cloning_format.initialize_on_transport(target_transport)
1101
# if a stacked branch wasn't requested, we don't create one
1102
# even if the origin was stacked
1103
stacked_branch_url = None
1104
if source_branch is not None:
1106
stacked_branch_url = self.root_transport.base
1107
source_repository = source_branch.repository
1110
source_branch = self.open_branch()
1111
source_repository = source_branch.repository
1113
stacked_branch_url = self.root_transport.base
1114
except errors.NotBranchError:
1115
source_branch = None
1117
source_repository = self.open_repository()
1118
except errors.NoRepositoryPresent:
1119
source_repository = None
1120
repository_policy = result.determine_repository_policy(
1121
force_new_repo, stacked_branch_url, require_stacking=stacked)
1122
result_repo, is_new_repo = repository_policy.acquire_repository()
1123
if is_new_repo and revision_id is not None and not stacked:
1124
fetch_spec = graph.PendingAncestryResult(
1125
[revision_id], source_repository)
1128
if source_repository is not None:
1129
# Fetch while stacked to prevent unstacked fetch from
1131
if fetch_spec is None:
1132
result_repo.fetch(source_repository, revision_id=revision_id)
1134
result_repo.fetch(source_repository, fetch_spec=fetch_spec)
1136
if source_branch is None:
1137
# this is for sprouting a bzrdir without a branch; is that
1139
# Not especially, but it's part of the contract.
1140
result_branch = result.create_branch()
1142
result_branch = source_branch.sprout(result,
1143
revision_id=revision_id, repository_policy=repository_policy)
1144
mutter("created new branch %r" % (result_branch,))
1146
# Create/update the result working tree
1147
if (create_tree_if_local and
1148
isinstance(target_transport, local.LocalTransport) and
1149
(result_repo is None or result_repo.make_working_trees())):
1150
wt = result.create_workingtree(accelerator_tree=accelerator_tree,
1154
if wt.path2id('') is None:
1156
wt.set_root_id(self.open_workingtree.get_root_id())
1157
except errors.NoWorkingTree:
1163
if recurse == 'down':
1165
basis = wt.basis_tree()
1167
subtrees = basis.iter_references()
1168
elif result_branch is not None:
1169
basis = result_branch.basis_tree()
1171
subtrees = basis.iter_references()
1172
elif source_branch is not None:
1173
basis = source_branch.basis_tree()
1175
subtrees = basis.iter_references()
1180
for path, file_id in subtrees:
1181
target = urlutils.join(url, urlutils.escape(path))
1182
sublocation = source_branch.reference_parent(file_id, path)
1183
sublocation.bzrdir.sprout(target,
1184
basis.get_reference_revision(file_id, path),
1185
force_new_repo=force_new_repo, recurse=recurse,
1188
if basis is not None:
1193
class BzrDirPreSplitOut(BzrDir):
1194
"""A common class for the all-in-one formats."""
1196
def __init__(self, _transport, _format):
1197
"""See BzrDir.__init__."""
1198
super(BzrDirPreSplitOut, self).__init__(_transport, _format)
1199
self._control_files = lockable_files.LockableFiles(
1200
self.get_branch_transport(None),
1201
self._format._lock_file_name,
1202
self._format._lock_class)
1204
def break_lock(self):
1205
"""Pre-splitout bzrdirs do not suffer from stale locks."""
1206
raise NotImplementedError(self.break_lock)
1208
def cloning_metadir(self, require_stacking=False):
1209
"""Produce a metadir suitable for cloning with."""
1210
if require_stacking:
1211
return format_registry.make_bzrdir('1.6')
1212
return self._format.__class__()
1214
def clone(self, url, revision_id=None, force_new_repo=False,
1215
preserve_stacking=False):
1216
"""See BzrDir.clone().
1218
force_new_repo has no effect, since this family of formats always
1219
require a new repository.
1220
preserve_stacking has no effect, since no source branch using this
1221
family of formats can be stacked, so there is no stacking to preserve.
1223
self._make_tail(url)
1224
result = self._format._initialize_for_clone(url)
1225
self.open_repository().clone(result, revision_id=revision_id)
1226
from_branch = self.open_branch()
1227
from_branch.clone(result, revision_id=revision_id)
1229
tree = self.open_workingtree()
1230
except errors.NotLocalUrl:
1231
# make a new one, this format always has to have one.
1232
result._init_workingtree()
1237
def create_branch(self):
1238
"""See BzrDir.create_branch."""
1239
return self._format.get_branch_format().initialize(self)
1241
def destroy_branch(self):
1242
"""See BzrDir.destroy_branch."""
1243
raise errors.UnsupportedOperation(self.destroy_branch, self)
1245
def create_repository(self, shared=False):
1246
"""See BzrDir.create_repository."""
1248
raise errors.IncompatibleFormat('shared repository', self._format)
1249
return self.open_repository()
1251
def destroy_repository(self):
1252
"""See BzrDir.destroy_repository."""
1253
raise errors.UnsupportedOperation(self.destroy_repository, self)
1255
def create_workingtree(self, revision_id=None, from_branch=None,
1256
accelerator_tree=None, hardlink=False):
1257
"""See BzrDir.create_workingtree."""
1258
# The workingtree is sometimes created when the bzrdir is created,
1259
# but not when cloning.
1261
# this looks buggy but is not -really-
1262
# because this format creates the workingtree when the bzrdir is
1264
# clone and sprout will have set the revision_id
1265
# and that will have set it for us, its only
1266
# specific uses of create_workingtree in isolation
1267
# that can do wonky stuff here, and that only
1268
# happens for creating checkouts, which cannot be
1269
# done on this format anyway. So - acceptable wart.
1271
result = self.open_workingtree(recommend_upgrade=False)
1272
except errors.NoSuchFile:
1273
result = self._init_workingtree()
1274
if revision_id is not None:
1275
if revision_id == _mod_revision.NULL_REVISION:
1276
result.set_parent_ids([])
1278
result.set_parent_ids([revision_id])
1281
def _init_workingtree(self):
1282
from bzrlib.workingtree import WorkingTreeFormat2
1284
return WorkingTreeFormat2().initialize(self)
1285
except errors.NotLocalUrl:
1286
# Even though we can't access the working tree, we need to
1287
# create its control files.
1288
return WorkingTreeFormat2()._stub_initialize_on_transport(
1289
self.transport, self._control_files._file_mode)
1291
def destroy_workingtree(self):
1292
"""See BzrDir.destroy_workingtree."""
1293
raise errors.UnsupportedOperation(self.destroy_workingtree, self)
1295
def destroy_workingtree_metadata(self):
1296
"""See BzrDir.destroy_workingtree_metadata."""
1297
raise errors.UnsupportedOperation(self.destroy_workingtree_metadata,
1300
def get_branch_transport(self, branch_format):
1301
"""See BzrDir.get_branch_transport()."""
1302
if branch_format is None:
1303
return self.transport
1305
branch_format.get_format_string()
1306
except NotImplementedError:
1307
return self.transport
1308
raise errors.IncompatibleFormat(branch_format, self._format)
1310
def get_repository_transport(self, repository_format):
1311
"""See BzrDir.get_repository_transport()."""
1312
if repository_format is None:
1313
return self.transport
1315
repository_format.get_format_string()
1316
except NotImplementedError:
1317
return self.transport
1318
raise errors.IncompatibleFormat(repository_format, self._format)
1320
def get_workingtree_transport(self, workingtree_format):
1321
"""See BzrDir.get_workingtree_transport()."""
1322
if workingtree_format is None:
1323
return self.transport
1325
workingtree_format.get_format_string()
1326
except NotImplementedError:
1327
return self.transport
1328
raise errors.IncompatibleFormat(workingtree_format, self._format)
1330
def needs_format_conversion(self, format=None):
1331
"""See BzrDir.needs_format_conversion()."""
1332
# if the format is not the same as the system default,
1333
# an upgrade is needed.
1335
symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
1336
% 'needs_format_conversion(format=None)')
1337
format = BzrDirFormat.get_default_format()
1338
return not isinstance(self._format, format.__class__)
1340
def open_branch(self, unsupported=False):
1341
"""See BzrDir.open_branch."""
1342
from bzrlib.branch import BzrBranchFormat4
1343
format = BzrBranchFormat4()
1344
self._check_supported(format, unsupported)
1345
return format.open(self, _found=True)
1347
def sprout(self, url, revision_id=None, force_new_repo=False,
1348
possible_transports=None, accelerator_tree=None,
1349
hardlink=False, stacked=False, create_tree_if_local=True,
1350
source_branch=None):
1351
"""See BzrDir.sprout()."""
1352
if source_branch is not None:
1353
my_branch = self.open_branch()
1354
if source_branch.base != my_branch.base:
1355
raise AssertionError(
1356
"source branch %r is not within %r with branch %r" %
1357
(source_branch, self, my_branch))
1359
raise errors.UnstackableBranchFormat(
1360
self._format, self.root_transport.base)
1361
if not create_tree_if_local:
1362
raise errors.MustHaveWorkingTree(
1363
self._format, self.root_transport.base)
1364
from bzrlib.workingtree import WorkingTreeFormat2
1365
self._make_tail(url)
1366
result = self._format._initialize_for_clone(url)
1368
self.open_repository().clone(result, revision_id=revision_id)
1369
except errors.NoRepositoryPresent:
1372
self.open_branch().sprout(result, revision_id=revision_id)
1373
except errors.NotBranchError:
1376
# we always want a working tree
1377
WorkingTreeFormat2().initialize(result,
1378
accelerator_tree=accelerator_tree,
1383
class BzrDir4(BzrDirPreSplitOut):
1384
"""A .bzr version 4 control object.
1386
This is a deprecated format and may be removed after sept 2006.
1389
def create_repository(self, shared=False):
1390
"""See BzrDir.create_repository."""
1391
return self._format.repository_format.initialize(self, shared)
1393
def needs_format_conversion(self, format=None):
1394
"""Format 4 dirs are always in need of conversion."""
1396
symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
1397
% 'needs_format_conversion(format=None)')
1400
def open_repository(self):
1401
"""See BzrDir.open_repository."""
1402
from bzrlib.repofmt.weaverepo import RepositoryFormat4
1403
return RepositoryFormat4().open(self, _found=True)
1406
class BzrDir5(BzrDirPreSplitOut):
1407
"""A .bzr version 5 control object.
1409
This is a deprecated format and may be removed after sept 2006.
1412
def open_repository(self):
1413
"""See BzrDir.open_repository."""
1414
from bzrlib.repofmt.weaverepo import RepositoryFormat5
1415
return RepositoryFormat5().open(self, _found=True)
1417
def open_workingtree(self, _unsupported=False,
1418
recommend_upgrade=True):
1419
"""See BzrDir.create_workingtree."""
1420
from bzrlib.workingtree import WorkingTreeFormat2
1421
wt_format = WorkingTreeFormat2()
1422
# we don't warn here about upgrades; that ought to be handled for the
1424
return wt_format.open(self, _found=True)
1427
class BzrDir6(BzrDirPreSplitOut):
1428
"""A .bzr version 6 control object.
1430
This is a deprecated format and may be removed after sept 2006.
1433
def open_repository(self):
1434
"""See BzrDir.open_repository."""
1435
from bzrlib.repofmt.weaverepo import RepositoryFormat6
1436
return RepositoryFormat6().open(self, _found=True)
1438
def open_workingtree(self, _unsupported=False,
1439
recommend_upgrade=True):
1440
"""See BzrDir.create_workingtree."""
1441
# we don't warn here about upgrades; that ought to be handled for the
1443
from bzrlib.workingtree import WorkingTreeFormat2
1444
return WorkingTreeFormat2().open(self, _found=True)
1447
class BzrDirMeta1(BzrDir):
1448
"""A .bzr meta version 1 control object.
1450
This is the first control object where the
1451
individual aspects are really split out: there are separate repository,
1452
workingtree and branch subdirectories and any subset of the three can be
1453
present within a BzrDir.
1456
def can_convert_format(self):
1457
"""See BzrDir.can_convert_format()."""
1460
def create_branch(self):
1461
"""See BzrDir.create_branch."""
1462
return self._format.get_branch_format().initialize(self)
1464
def destroy_branch(self):
1465
"""See BzrDir.create_branch."""
1466
self.transport.delete_tree('branch')
1468
def create_repository(self, shared=False):
1469
"""See BzrDir.create_repository."""
1470
return self._format.repository_format.initialize(self, shared)
1472
def destroy_repository(self):
1473
"""See BzrDir.destroy_repository."""
1474
self.transport.delete_tree('repository')
1476
def create_workingtree(self, revision_id=None, from_branch=None,
1477
accelerator_tree=None, hardlink=False):
1478
"""See BzrDir.create_workingtree."""
1479
return self._format.workingtree_format.initialize(
1480
self, revision_id, from_branch=from_branch,
1481
accelerator_tree=accelerator_tree, hardlink=hardlink)
1483
def destroy_workingtree(self):
1484
"""See BzrDir.destroy_workingtree."""
1485
wt = self.open_workingtree(recommend_upgrade=False)
1486
repository = wt.branch.repository
1487
empty = repository.revision_tree(_mod_revision.NULL_REVISION)
1488
wt.revert(old_tree=empty)
1489
self.destroy_workingtree_metadata()
1491
def destroy_workingtree_metadata(self):
1492
self.transport.delete_tree('checkout')
1494
def find_branch_format(self):
1495
"""Find the branch 'format' for this bzrdir.
1497
This might be a synthetic object for e.g. RemoteBranch and SVN.
1499
from bzrlib.branch import BranchFormat
1500
return BranchFormat.find_format(self)
1502
def _get_mkdir_mode(self):
1503
"""Figure out the mode to use when creating a bzrdir subdir."""
1504
temp_control = lockable_files.LockableFiles(self.transport, '',
1505
lockable_files.TransportLock)
1506
return temp_control._dir_mode
1508
def get_branch_reference(self):
1509
"""See BzrDir.get_branch_reference()."""
1510
from bzrlib.branch import BranchFormat
1511
format = BranchFormat.find_format(self)
1512
return format.get_reference(self)
1514
def get_branch_transport(self, branch_format):
1515
"""See BzrDir.get_branch_transport()."""
1516
if branch_format is None:
1517
return self.transport.clone('branch')
1519
branch_format.get_format_string()
1520
except NotImplementedError:
1521
raise errors.IncompatibleFormat(branch_format, self._format)
1523
self.transport.mkdir('branch', mode=self._get_mkdir_mode())
1524
except errors.FileExists:
1526
return self.transport.clone('branch')
1528
def get_repository_transport(self, repository_format):
1529
"""See BzrDir.get_repository_transport()."""
1530
if repository_format is None:
1531
return self.transport.clone('repository')
1533
repository_format.get_format_string()
1534
except NotImplementedError:
1535
raise errors.IncompatibleFormat(repository_format, self._format)
1537
self.transport.mkdir('repository', mode=self._get_mkdir_mode())
1538
except errors.FileExists:
1540
return self.transport.clone('repository')
1542
def get_workingtree_transport(self, workingtree_format):
1543
"""See BzrDir.get_workingtree_transport()."""
1544
if workingtree_format is None:
1545
return self.transport.clone('checkout')
1547
workingtree_format.get_format_string()
1548
except NotImplementedError:
1549
raise errors.IncompatibleFormat(workingtree_format, self._format)
1551
self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
1552
except errors.FileExists:
1554
return self.transport.clone('checkout')
1556
def needs_format_conversion(self, format=None):
1557
"""See BzrDir.needs_format_conversion()."""
1559
symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
1560
% 'needs_format_conversion(format=None)')
1562
format = BzrDirFormat.get_default_format()
1563
if not isinstance(self._format, format.__class__):
1564
# it is not a meta dir format, conversion is needed.
1566
# we might want to push this down to the repository?
1568
if not isinstance(self.open_repository()._format,
1569
format.repository_format.__class__):
1570
# the repository needs an upgrade.
1572
except errors.NoRepositoryPresent:
1575
if not isinstance(self.open_branch()._format,
1576
format.get_branch_format().__class__):
1577
# the branch needs an upgrade.
1579
except errors.NotBranchError:
1582
my_wt = self.open_workingtree(recommend_upgrade=False)
1583
if not isinstance(my_wt._format,
1584
format.workingtree_format.__class__):
1585
# the workingtree needs an upgrade.
1587
except (errors.NoWorkingTree, errors.NotLocalUrl):
1591
def open_branch(self, unsupported=False):
1592
"""See BzrDir.open_branch."""
1593
format = self.find_branch_format()
1594
self._check_supported(format, unsupported)
1595
return format.open(self, _found=True)
1597
def open_repository(self, unsupported=False):
1598
"""See BzrDir.open_repository."""
1599
from bzrlib.repository import RepositoryFormat
1600
format = RepositoryFormat.find_format(self)
1601
self._check_supported(format, unsupported)
1602
return format.open(self, _found=True)
1604
def open_workingtree(self, unsupported=False,
1605
recommend_upgrade=True):
1606
"""See BzrDir.open_workingtree."""
1607
from bzrlib.workingtree import WorkingTreeFormat
1608
format = WorkingTreeFormat.find_format(self)
1609
self._check_supported(format, unsupported,
1611
basedir=self.root_transport.base)
1612
return format.open(self, _found=True)
1614
def _get_config(self):
1615
return config.BzrDirConfig(self.transport)
1618
class BzrDirFormat(object):
1619
"""An encapsulation of the initialization and open routines for a format.
1621
Formats provide three things:
1622
* An initialization routine,
1626
Formats are placed in a dict by their format string for reference
1627
during bzrdir opening. These should be subclasses of BzrDirFormat
1630
Once a format is deprecated, just deprecate the initialize and open
1631
methods on the format class. Do not deprecate the object, as the
1632
object will be created every system load.
1635
_default_format = None
1636
"""The default format used for new .bzr dirs."""
1639
"""The known formats."""
1641
_control_formats = []
1642
"""The registered control formats - .bzr, ....
1644
This is a list of BzrDirFormat objects.
1647
_control_server_formats = []
1648
"""The registered control server formats, e.g. RemoteBzrDirs.
1650
This is a list of BzrDirFormat objects.
1653
_lock_file_name = 'branch-lock'
1655
# _lock_class must be set in subclasses to the lock type, typ.
1656
# TransportLock or LockDir
1659
def find_format(klass, transport, _server_formats=True):
1660
"""Return the format present at transport."""
1662
formats = klass._control_server_formats + klass._control_formats
1664
formats = klass._control_formats
1665
for format in formats:
1667
return format.probe_transport(transport)
1668
except errors.NotBranchError:
1669
# this format does not find a control dir here.
1671
raise errors.NotBranchError(path=transport.base)
1674
def probe_transport(klass, transport):
1675
"""Return the .bzrdir style format present in a directory."""
1677
format_string = transport.get(".bzr/branch-format").read()
1678
except errors.NoSuchFile:
1679
raise errors.NotBranchError(path=transport.base)
1682
return klass._formats[format_string]
1684
raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
1687
def get_default_format(klass):
1688
"""Return the current default format."""
1689
return klass._default_format
1691
def get_format_string(self):
1692
"""Return the ASCII format string that identifies this format."""
1693
raise NotImplementedError(self.get_format_string)
1695
def get_format_description(self):
1696
"""Return the short description for this format."""
1697
raise NotImplementedError(self.get_format_description)
1699
def get_converter(self, format=None):
1700
"""Return the converter to use to convert bzrdirs needing converts.
1702
This returns a bzrlib.bzrdir.Converter object.
1704
This should return the best upgrader to step this format towards the
1705
current default format. In the case of plugins we can/should provide
1706
some means for them to extend the range of returnable converters.
1708
:param format: Optional format to override the default format of the
1711
raise NotImplementedError(self.get_converter)
1713
def initialize(self, url, possible_transports=None):
1714
"""Create a bzr control dir at this url and return an opened copy.
1716
Subclasses should typically override initialize_on_transport
1717
instead of this method.
1719
return self.initialize_on_transport(get_transport(url,
1720
possible_transports))
1722
def initialize_on_transport(self, transport):
1723
"""Initialize a new bzrdir in the base directory of a Transport."""
1725
# can we hand off the request to the smart server rather than using
1727
client_medium = transport.get_smart_medium()
1728
except errors.NoSmartMedium:
1729
return self._initialize_on_transport_vfs(transport)
1731
# Current RPC's only know how to create bzr metadir1 instances, so
1732
# we still delegate to vfs methods if the requested format is not a
1734
if type(self) != BzrDirMetaFormat1:
1735
return self._initialize_on_transport_vfs(transport)
1736
remote_format = RemoteBzrDirFormat()
1737
self._supply_sub_formats_to(remote_format)
1738
return remote_format.initialize_on_transport(transport)
1740
def _initialize_on_transport_vfs(self, transport):
1741
"""Initialize a new bzrdir using VFS calls.
1743
:param transport: The transport to create the .bzr directory in.
1746
# Since we are creating a .bzr directory, inherit the
1747
# mode from the root directory
1748
temp_control = lockable_files.LockableFiles(transport,
1749
'', lockable_files.TransportLock)
1750
temp_control._transport.mkdir('.bzr',
1751
# FIXME: RBC 20060121 don't peek under
1753
mode=temp_control._dir_mode)
1754
if sys.platform == 'win32' and isinstance(transport, local.LocalTransport):
1755
win32utils.set_file_attr_hidden(transport._abspath('.bzr'))
1756
file_mode = temp_control._file_mode
1758
bzrdir_transport = transport.clone('.bzr')
1759
utf8_files = [('README',
1760
"This is a Bazaar control directory.\n"
1761
"Do not change any files in this directory.\n"
1762
"See http://bazaar-vcs.org/ for more information about Bazaar.\n"),
1763
('branch-format', self.get_format_string()),
1765
# NB: no need to escape relative paths that are url safe.
1766
control_files = lockable_files.LockableFiles(bzrdir_transport,
1767
self._lock_file_name, self._lock_class)
1768
control_files.create_lock()
1769
control_files.lock_write()
1771
for (filename, content) in utf8_files:
1772
bzrdir_transport.put_bytes(filename, content,
1775
control_files.unlock()
1776
return self.open(transport, _found=True)
1778
def is_supported(self):
1779
"""Is this format supported?
1781
Supported formats must be initializable and openable.
1782
Unsupported formats may not support initialization or committing or
1783
some other features depending on the reason for not being supported.
1787
def network_name(self):
1788
"""A simple byte string uniquely identifying this format for RPC calls.
1790
Bzr control formats use thir disk format string to identify the format
1791
over the wire. Its possible that other control formats have more
1792
complex detection requirements, so we permit them to use any unique and
1793
immutable string they desire.
1795
raise NotImplementedError(self.network_name)
1797
def same_model(self, target_format):
1798
return (self.repository_format.rich_root_data ==
1799
target_format.rich_root_data)
1802
def known_formats(klass):
1803
"""Return all the known formats.
1805
Concrete formats should override _known_formats.
1807
# There is double indirection here to make sure that control
1808
# formats used by more than one dir format will only be probed
1809
# once. This can otherwise be quite expensive for remote connections.
1811
for format in klass._control_formats:
1812
result.update(format._known_formats())
1816
def _known_formats(klass):
1817
"""Return the known format instances for this control format."""
1818
return set(klass._formats.values())
1820
def open(self, transport, _found=False):
1821
"""Return an instance of this format for the dir transport points at.
1823
_found is a private parameter, do not use it.
1826
found_format = BzrDirFormat.find_format(transport)
1827
if not isinstance(found_format, self.__class__):
1828
raise AssertionError("%s was asked to open %s, but it seems to need "
1830
% (self, transport, found_format))
1831
# Allow subclasses - use the found format.
1832
self._supply_sub_formats_to(found_format)
1833
return found_format._open(transport)
1834
return self._open(transport)
1836
def _open(self, transport):
1837
"""Template method helper for opening BzrDirectories.
1839
This performs the actual open and any additional logic or parameter
1842
raise NotImplementedError(self._open)
1845
def register_format(klass, format):
1846
klass._formats[format.get_format_string()] = format
1847
# bzr native formats have a network name of their format string.
1848
network_format_registry.register(format.get_format_string(), format.__class__)
1851
def register_control_format(klass, format):
1852
"""Register a format that does not use '.bzr' for its control dir.
1854
TODO: This should be pulled up into a 'ControlDirFormat' base class
1855
which BzrDirFormat can inherit from, and renamed to register_format
1856
there. It has been done without that for now for simplicity of
1859
klass._control_formats.append(format)
1862
def register_control_server_format(klass, format):
1863
"""Register a control format for client-server environments.
1865
These formats will be tried before ones registered with
1866
register_control_format. This gives implementations that decide to the
1867
chance to grab it before anything looks at the contents of the format
1870
klass._control_server_formats.append(format)
1873
def _set_default_format(klass, format):
1874
"""Set default format (for testing behavior of defaults only)"""
1875
klass._default_format = format
1879
return self.get_format_description().rstrip()
1881
def _supply_sub_formats_to(self, other_format):
1882
"""Give other_format the same values for sub formats as this has.
1884
This method is expected to be used when parameterising a
1885
RemoteBzrDirFormat instance with the parameters from a
1886
BzrDirMetaFormat1 instance.
1888
:param other_format: other_format is a format which should be
1889
compatible with whatever sub formats are supported by self.
1894
def unregister_format(klass, format):
1895
del klass._formats[format.get_format_string()]
1898
def unregister_control_format(klass, format):
1899
klass._control_formats.remove(format)
1902
class BzrDirFormat4(BzrDirFormat):
1903
"""Bzr dir format 4.
1905
This format is a combined format for working tree, branch and repository.
1907
- Format 1 working trees [always]
1908
- Format 4 branches [always]
1909
- Format 4 repositories [always]
1911
This format is deprecated: it indexes texts using a text it which is
1912
removed in format 5; write support for this format has been removed.
1915
_lock_class = lockable_files.TransportLock
1917
def get_format_string(self):
1918
"""See BzrDirFormat.get_format_string()."""
1919
return "Bazaar-NG branch, format 0.0.4\n"
1921
def get_format_description(self):
1922
"""See BzrDirFormat.get_format_description()."""
1923
return "All-in-one format 4"
1925
def get_converter(self, format=None):
1926
"""See BzrDirFormat.get_converter()."""
1927
# there is one and only one upgrade path here.
1928
return ConvertBzrDir4To5()
1930
def initialize_on_transport(self, transport):
1931
"""Format 4 branches cannot be created."""
1932
raise errors.UninitializableFormat(self)
1934
def is_supported(self):
1935
"""Format 4 is not supported.
1937
It is not supported because the model changed from 4 to 5 and the
1938
conversion logic is expensive - so doing it on the fly was not
1943
def network_name(self):
1944
return self.get_format_string()
1946
def _open(self, transport):
1947
"""See BzrDirFormat._open."""
1948
return BzrDir4(transport, self)
1950
def __return_repository_format(self):
1951
"""Circular import protection."""
1952
from bzrlib.repofmt.weaverepo import RepositoryFormat4
1953
return RepositoryFormat4()
1954
repository_format = property(__return_repository_format)
1957
class BzrDirFormat5(BzrDirFormat):
1958
"""Bzr control format 5.
1960
This format is a combined format for working tree, branch and repository.
1962
- Format 2 working trees [always]
1963
- Format 4 branches [always]
1964
- Format 5 repositories [always]
1965
Unhashed stores in the repository.
1968
_lock_class = lockable_files.TransportLock
1970
def get_format_string(self):
1971
"""See BzrDirFormat.get_format_string()."""
1972
return "Bazaar-NG branch, format 5\n"
1974
def get_branch_format(self):
1975
from bzrlib import branch
1976
return branch.BzrBranchFormat4()
1978
def get_format_description(self):
1979
"""See BzrDirFormat.get_format_description()."""
1980
return "All-in-one format 5"
1982
def get_converter(self, format=None):
1983
"""See BzrDirFormat.get_converter()."""
1984
# there is one and only one upgrade path here.
1985
return ConvertBzrDir5To6()
1987
def _initialize_for_clone(self, url):
1988
return self.initialize_on_transport(get_transport(url), _cloning=True)
1990
def initialize_on_transport(self, transport, _cloning=False):
1991
"""Format 5 dirs always have working tree, branch and repository.
1993
Except when they are being cloned.
1995
from bzrlib.branch import BzrBranchFormat4
1996
from bzrlib.repofmt.weaverepo import RepositoryFormat5
1997
result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
1998
RepositoryFormat5().initialize(result, _internal=True)
2000
branch = BzrBranchFormat4().initialize(result)
2001
result._init_workingtree()
2004
def network_name(self):
2005
return self.get_format_string()
2007
def _open(self, transport):
2008
"""See BzrDirFormat._open."""
2009
return BzrDir5(transport, self)
2011
def __return_repository_format(self):
2012
"""Circular import protection."""
2013
from bzrlib.repofmt.weaverepo import RepositoryFormat5
2014
return RepositoryFormat5()
2015
repository_format = property(__return_repository_format)
2018
class BzrDirFormat6(BzrDirFormat):
2019
"""Bzr control format 6.
2021
This format is a combined format for working tree, branch and repository.
2023
- Format 2 working trees [always]
2024
- Format 4 branches [always]
2025
- Format 6 repositories [always]
2028
_lock_class = lockable_files.TransportLock
2030
def get_format_string(self):
2031
"""See BzrDirFormat.get_format_string()."""
2032
return "Bazaar-NG branch, format 6\n"
2034
def get_format_description(self):
2035
"""See BzrDirFormat.get_format_description()."""
2036
return "All-in-one format 6"
2038
def get_branch_format(self):
2039
from bzrlib import branch
2040
return branch.BzrBranchFormat4()
2042
def get_converter(self, format=None):
2043
"""See BzrDirFormat.get_converter()."""
2044
# there is one and only one upgrade path here.
2045
return ConvertBzrDir6ToMeta()
2047
def _initialize_for_clone(self, url):
2048
return self.initialize_on_transport(get_transport(url), _cloning=True)
2050
def initialize_on_transport(self, transport, _cloning=False):
2051
"""Format 6 dirs always have working tree, branch and repository.
2053
Except when they are being cloned.
2055
from bzrlib.branch import BzrBranchFormat4
2056
from bzrlib.repofmt.weaverepo import RepositoryFormat6
2057
result = super(BzrDirFormat6, self).initialize_on_transport(transport)
2058
RepositoryFormat6().initialize(result, _internal=True)
2060
branch = BzrBranchFormat4().initialize(result)
2061
result._init_workingtree()
2064
def network_name(self):
2065
return self.get_format_string()
2067
def _open(self, transport):
2068
"""See BzrDirFormat._open."""
2069
return BzrDir6(transport, self)
2071
def __return_repository_format(self):
2072
"""Circular import protection."""
2073
from bzrlib.repofmt.weaverepo import RepositoryFormat6
2074
return RepositoryFormat6()
2075
repository_format = property(__return_repository_format)
2078
class BzrDirMetaFormat1(BzrDirFormat):
2079
"""Bzr meta control format 1
2081
This is the first format with split out working tree, branch and repository
2084
- Format 3 working trees [optional]
2085
- Format 5 branches [optional]
2086
- Format 7 repositories [optional]
2089
_lock_class = lockdir.LockDir
2092
self._workingtree_format = None
2093
self._branch_format = None
2094
self._repository_format = None
2096
def __eq__(self, other):
2097
if other.__class__ is not self.__class__:
2099
if other.repository_format != self.repository_format:
2101
if other.workingtree_format != self.workingtree_format:
2105
def __ne__(self, other):
2106
return not self == other
2108
def get_branch_format(self):
2109
if self._branch_format is None:
2110
from bzrlib.branch import BranchFormat
2111
self._branch_format = BranchFormat.get_default_format()
2112
return self._branch_format
2114
def set_branch_format(self, format):
2115
self._branch_format = format
2117
def require_stacking(self):
2118
if not self.get_branch_format().supports_stacking():
2119
# We need to make a stacked branch, but the default format for the
2120
# target doesn't support stacking. So force a branch that *can*
2122
from bzrlib.branch import BzrBranchFormat7
2123
branch_format = BzrBranchFormat7()
2124
self.set_branch_format(branch_format)
2125
mutter("using %r for stacking" % (branch_format,))
2126
from bzrlib.repofmt import pack_repo
2127
if self.repository_format.rich_root_data:
2128
bzrdir_format_name = '1.6.1-rich-root'
2129
repo_format = pack_repo.RepositoryFormatKnitPack5RichRoot()
2131
bzrdir_format_name = '1.6'
2132
repo_format = pack_repo.RepositoryFormatKnitPack5()
2133
note('Source format does not support stacking, using format:'
2135
bzrdir_format_name, repo_format.get_format_description())
2136
self.repository_format = repo_format
2138
def get_converter(self, format=None):
2139
"""See BzrDirFormat.get_converter()."""
2141
format = BzrDirFormat.get_default_format()
2142
if not isinstance(self, format.__class__):
2143
# converting away from metadir is not implemented
2144
raise NotImplementedError(self.get_converter)
2145
return ConvertMetaToMeta(format)
2147
def get_format_string(self):
2148
"""See BzrDirFormat.get_format_string()."""
2149
return "Bazaar-NG meta directory, format 1\n"
2151
def get_format_description(self):
2152
"""See BzrDirFormat.get_format_description()."""
2153
return "Meta directory format 1"
2155
def network_name(self):
2156
return self.get_format_string()
2158
def _open(self, transport):
2159
"""See BzrDirFormat._open."""
2160
return BzrDirMeta1(transport, self)
2162
def __return_repository_format(self):
2163
"""Circular import protection."""
2164
if self._repository_format:
2165
return self._repository_format
2166
from bzrlib.repository import RepositoryFormat
2167
return RepositoryFormat.get_default_format()
2169
def _set_repository_format(self, value):
2170
"""Allow changing the repository format for metadir formats."""
2171
self._repository_format = value
2173
repository_format = property(__return_repository_format,
2174
_set_repository_format)
2176
def _supply_sub_formats_to(self, other_format):
2177
"""Give other_format the same values for sub formats as this has.
2179
This method is expected to be used when parameterising a
2180
RemoteBzrDirFormat instance with the parameters from a
2181
BzrDirMetaFormat1 instance.
2183
:param other_format: other_format is a format which should be
2184
compatible with whatever sub formats are supported by self.
2187
if getattr(self, '_repository_format', None) is not None:
2188
other_format.repository_format = self.repository_format
2189
if self._branch_format is not None:
2190
other_format._branch_format = self._branch_format
2191
if self._workingtree_format is not None:
2192
other_format.workingtree_format = self.workingtree_format
2194
def __get_workingtree_format(self):
2195
if self._workingtree_format is None:
2196
from bzrlib.workingtree import WorkingTreeFormat
2197
self._workingtree_format = WorkingTreeFormat.get_default_format()
2198
return self._workingtree_format
2200
def __set_workingtree_format(self, wt_format):
2201
self._workingtree_format = wt_format
2203
workingtree_format = property(__get_workingtree_format,
2204
__set_workingtree_format)
2207
network_format_registry = registry.FormatRegistry()
2208
"""Registry of formats indexed by their network name.
2210
The network name for a BzrDirFormat is an identifier that can be used when
2211
referring to formats with smart server operations. See
2212
BzrDirFormat.network_name() for more detail.
2216
# Register bzr control format
2217
BzrDirFormat.register_control_format(BzrDirFormat)
2219
# Register bzr formats
2220
BzrDirFormat.register_format(BzrDirFormat4())
2221
BzrDirFormat.register_format(BzrDirFormat5())
2222
BzrDirFormat.register_format(BzrDirFormat6())
2223
__default_format = BzrDirMetaFormat1()
2224
BzrDirFormat.register_format(__default_format)
2225
BzrDirFormat._default_format = __default_format
2228
class Converter(object):
2229
"""Converts a disk format object from one format to another."""
2231
def convert(self, to_convert, pb):
2232
"""Perform the conversion of to_convert, giving feedback via pb.
2234
:param to_convert: The disk object to convert.
2235
:param pb: a progress bar to use for progress information.
2238
def step(self, message):
2239
"""Update the pb by a step."""
2241
self.pb.update(message, self.count, self.total)
2244
class ConvertBzrDir4To5(Converter):
2245
"""Converts format 4 bzr dirs to format 5."""
2248
super(ConvertBzrDir4To5, self).__init__()
2249
self.converted_revs = set()
2250
self.absent_revisions = set()
2254
def convert(self, to_convert, pb):
2255
"""See Converter.convert()."""
2256
self.bzrdir = to_convert
2258
self.pb.note('starting upgrade from format 4 to 5')
2259
if isinstance(self.bzrdir.transport, local.LocalTransport):
2260
self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
2261
self._convert_to_weaves()
2262
return BzrDir.open(self.bzrdir.root_transport.base)
2264
def _convert_to_weaves(self):
2265
self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
2268
stat = self.bzrdir.transport.stat('weaves')
2269
if not S_ISDIR(stat.st_mode):
2270
self.bzrdir.transport.delete('weaves')
2271
self.bzrdir.transport.mkdir('weaves')
2272
except errors.NoSuchFile:
2273
self.bzrdir.transport.mkdir('weaves')
2274
# deliberately not a WeaveFile as we want to build it up slowly.
2275
self.inv_weave = Weave('inventory')
2276
# holds in-memory weaves for all files
2277
self.text_weaves = {}
2278
self.bzrdir.transport.delete('branch-format')
2279
self.branch = self.bzrdir.open_branch()
2280
self._convert_working_inv()
2281
rev_history = self.branch.revision_history()
2282
# to_read is a stack holding the revisions we still need to process;
2283
# appending to it adds new highest-priority revisions
2284
self.known_revisions = set(rev_history)
2285
self.to_read = rev_history[-1:]
2287
rev_id = self.to_read.pop()
2288
if (rev_id not in self.revisions
2289
and rev_id not in self.absent_revisions):
2290
self._load_one_rev(rev_id)
2292
to_import = self._make_order()
2293
for i, rev_id in enumerate(to_import):
2294
self.pb.update('converting revision', i, len(to_import))
2295
self._convert_one_rev(rev_id)
2297
self._write_all_weaves()
2298
self._write_all_revs()
2299
self.pb.note('upgraded to weaves:')
2300
self.pb.note(' %6d revisions and inventories', len(self.revisions))
2301
self.pb.note(' %6d revisions not present', len(self.absent_revisions))
2302
self.pb.note(' %6d texts', self.text_count)
2303
self._cleanup_spare_files_after_format4()
2304
self.branch._transport.put_bytes(
2306
BzrDirFormat5().get_format_string(),
2307
mode=self.bzrdir._get_file_mode())
2309
def _cleanup_spare_files_after_format4(self):
2310
# FIXME working tree upgrade foo.
2311
for n in 'merged-patches', 'pending-merged-patches':
2313
## assert os.path.getsize(p) == 0
2314
self.bzrdir.transport.delete(n)
2315
except errors.NoSuchFile:
2317
self.bzrdir.transport.delete_tree('inventory-store')
2318
self.bzrdir.transport.delete_tree('text-store')
2320
def _convert_working_inv(self):
2321
inv = xml4.serializer_v4.read_inventory(
2322
self.branch._transport.get('inventory'))
2323
new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
2324
self.branch._transport.put_bytes('inventory', new_inv_xml,
2325
mode=self.bzrdir._get_file_mode())
2327
def _write_all_weaves(self):
2328
controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
2329
weave_transport = self.bzrdir.transport.clone('weaves')
2330
weaves = WeaveStore(weave_transport, prefixed=False)
2331
transaction = WriteTransaction()
2335
for file_id, file_weave in self.text_weaves.items():
2336
self.pb.update('writing weave', i, len(self.text_weaves))
2337
weaves._put_weave(file_id, file_weave, transaction)
2339
self.pb.update('inventory', 0, 1)
2340
controlweaves._put_weave('inventory', self.inv_weave, transaction)
2341
self.pb.update('inventory', 1, 1)
2345
def _write_all_revs(self):
2346
"""Write all revisions out in new form."""
2347
self.bzrdir.transport.delete_tree('revision-store')
2348
self.bzrdir.transport.mkdir('revision-store')
2349
revision_transport = self.bzrdir.transport.clone('revision-store')
2351
from bzrlib.xml5 import serializer_v5
2352
from bzrlib.repofmt.weaverepo import RevisionTextStore
2353
revision_store = RevisionTextStore(revision_transport,
2354
serializer_v5, False, versionedfile.PrefixMapper(),
2355
lambda:True, lambda:True)
2357
for i, rev_id in enumerate(self.converted_revs):
2358
self.pb.update('write revision', i, len(self.converted_revs))
2359
text = serializer_v5.write_revision_to_string(
2360
self.revisions[rev_id])
2362
revision_store.add_lines(key, None, osutils.split_lines(text))
2366
def _load_one_rev(self, rev_id):
2367
"""Load a revision object into memory.
2369
Any parents not either loaded or abandoned get queued to be
2371
self.pb.update('loading revision',
2372
len(self.revisions),
2373
len(self.known_revisions))
2374
if not self.branch.repository.has_revision(rev_id):
2376
self.pb.note('revision {%s} not present in branch; '
2377
'will be converted as a ghost',
2379
self.absent_revisions.add(rev_id)
2381
rev = self.branch.repository.get_revision(rev_id)
2382
for parent_id in rev.parent_ids:
2383
self.known_revisions.add(parent_id)
2384
self.to_read.append(parent_id)
2385
self.revisions[rev_id] = rev
2387
def _load_old_inventory(self, rev_id):
2388
old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
2389
inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
2390
inv.revision_id = rev_id
2391
rev = self.revisions[rev_id]
2394
def _load_updated_inventory(self, rev_id):
2395
inv_xml = self.inv_weave.get_text(rev_id)
2396
inv = xml5.serializer_v5.read_inventory_from_string(inv_xml, rev_id)
2399
def _convert_one_rev(self, rev_id):
2400
"""Convert revision and all referenced objects to new format."""
2401
rev = self.revisions[rev_id]
2402
inv = self._load_old_inventory(rev_id)
2403
present_parents = [p for p in rev.parent_ids
2404
if p not in self.absent_revisions]
2405
self._convert_revision_contents(rev, inv, present_parents)
2406
self._store_new_inv(rev, inv, present_parents)
2407
self.converted_revs.add(rev_id)
2409
def _store_new_inv(self, rev, inv, present_parents):
2410
new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
2411
new_inv_sha1 = sha_string(new_inv_xml)
2412
self.inv_weave.add_lines(rev.revision_id,
2414
new_inv_xml.splitlines(True))
2415
rev.inventory_sha1 = new_inv_sha1
2417
def _convert_revision_contents(self, rev, inv, present_parents):
2418
"""Convert all the files within a revision.
2420
Also upgrade the inventory to refer to the text revision ids."""
2421
rev_id = rev.revision_id
2422
mutter('converting texts of revision {%s}',
2424
parent_invs = map(self._load_updated_inventory, present_parents)
2425
entries = inv.iter_entries()
2427
for path, ie in entries:
2428
self._convert_file_version(rev, ie, parent_invs)
2430
def _convert_file_version(self, rev, ie, parent_invs):
2431
"""Convert one version of one file.
2433
The file needs to be added into the weave if it is a merge
2434
of >=2 parents or if it's changed from its parent.
2436
file_id = ie.file_id
2437
rev_id = rev.revision_id
2438
w = self.text_weaves.get(file_id)
2441
self.text_weaves[file_id] = w
2442
text_changed = False
2443
parent_candiate_entries = ie.parent_candidates(parent_invs)
2444
heads = graph.Graph(self).heads(parent_candiate_entries.keys())
2445
# XXX: Note that this is unordered - and this is tolerable because
2446
# the previous code was also unordered.
2447
previous_entries = dict((head, parent_candiate_entries[head]) for head
2449
self.snapshot_ie(previous_entries, ie, w, rev_id)
2452
@symbol_versioning.deprecated_method(symbol_versioning.one_one)
2453
def get_parents(self, revision_ids):
2454
for revision_id in revision_ids:
2455
yield self.revisions[revision_id].parent_ids
2457
def get_parent_map(self, revision_ids):
2458
"""See graph._StackedParentsProvider.get_parent_map"""
2459
return dict((revision_id, self.revisions[revision_id])
2460
for revision_id in revision_ids
2461
if revision_id in self.revisions)
2463
def snapshot_ie(self, previous_revisions, ie, w, rev_id):
2464
# TODO: convert this logic, which is ~= snapshot to
2465
# a call to:. This needs the path figured out. rather than a work_tree
2466
# a v4 revision_tree can be given, or something that looks enough like
2467
# one to give the file content to the entry if it needs it.
2468
# and we need something that looks like a weave store for snapshot to
2470
#ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
2471
if len(previous_revisions) == 1:
2472
previous_ie = previous_revisions.values()[0]
2473
if ie._unchanged(previous_ie):
2474
ie.revision = previous_ie.revision
2477
text = self.branch.repository._text_store.get(ie.text_id)
2478
file_lines = text.readlines()
2479
w.add_lines(rev_id, previous_revisions, file_lines)
2480
self.text_count += 1
2482
w.add_lines(rev_id, previous_revisions, [])
2483
ie.revision = rev_id
2485
def _make_order(self):
2486
"""Return a suitable order for importing revisions.
2488
The order must be such that an revision is imported after all
2489
its (present) parents.
2491
todo = set(self.revisions.keys())
2492
done = self.absent_revisions.copy()
2495
# scan through looking for a revision whose parents
2497
for rev_id in sorted(list(todo)):
2498
rev = self.revisions[rev_id]
2499
parent_ids = set(rev.parent_ids)
2500
if parent_ids.issubset(done):
2501
# can take this one now
2502
order.append(rev_id)
2508
class ConvertBzrDir5To6(Converter):
2509
"""Converts format 5 bzr dirs to format 6."""
2511
def convert(self, to_convert, pb):
2512
"""See Converter.convert()."""
2513
self.bzrdir = to_convert
2515
self.pb.note('starting upgrade from format 5 to 6')
2516
self._convert_to_prefixed()
2517
return BzrDir.open(self.bzrdir.root_transport.base)
2519
def _convert_to_prefixed(self):
2520
from bzrlib.store import TransportStore
2521
self.bzrdir.transport.delete('branch-format')
2522
for store_name in ["weaves", "revision-store"]:
2523
self.pb.note("adding prefixes to %s" % store_name)
2524
store_transport = self.bzrdir.transport.clone(store_name)
2525
store = TransportStore(store_transport, prefixed=True)
2526
for urlfilename in store_transport.list_dir('.'):
2527
filename = urlutils.unescape(urlfilename)
2528
if (filename.endswith(".weave") or
2529
filename.endswith(".gz") or
2530
filename.endswith(".sig")):
2531
file_id, suffix = os.path.splitext(filename)
2535
new_name = store._mapper.map((file_id,)) + suffix
2536
# FIXME keep track of the dirs made RBC 20060121
2538
store_transport.move(filename, new_name)
2539
except errors.NoSuchFile: # catches missing dirs strangely enough
2540
store_transport.mkdir(osutils.dirname(new_name))
2541
store_transport.move(filename, new_name)
2542
self.bzrdir.transport.put_bytes(
2544
BzrDirFormat6().get_format_string(),
2545
mode=self.bzrdir._get_file_mode())
2548
class ConvertBzrDir6ToMeta(Converter):
2549
"""Converts format 6 bzr dirs to metadirs."""
2551
def convert(self, to_convert, pb):
2552
"""See Converter.convert()."""
2553
from bzrlib.repofmt.weaverepo import RepositoryFormat7
2554
from bzrlib.branch import BzrBranchFormat5
2555
self.bzrdir = to_convert
2558
self.total = 20 # the steps we know about
2559
self.garbage_inventories = []
2560
self.dir_mode = self.bzrdir._get_dir_mode()
2561
self.file_mode = self.bzrdir._get_file_mode()
2563
self.pb.note('starting upgrade from format 6 to metadir')
2564
self.bzrdir.transport.put_bytes(
2566
"Converting to format 6",
2567
mode=self.file_mode)
2568
# its faster to move specific files around than to open and use the apis...
2569
# first off, nuke ancestry.weave, it was never used.
2571
self.step('Removing ancestry.weave')
2572
self.bzrdir.transport.delete('ancestry.weave')
2573
except errors.NoSuchFile:
2575
# find out whats there
2576
self.step('Finding branch files')
2577
last_revision = self.bzrdir.open_branch().last_revision()
2578
bzrcontents = self.bzrdir.transport.list_dir('.')
2579
for name in bzrcontents:
2580
if name.startswith('basis-inventory.'):
2581
self.garbage_inventories.append(name)
2582
# create new directories for repository, working tree and branch
2583
repository_names = [('inventory.weave', True),
2584
('revision-store', True),
2586
self.step('Upgrading repository ')
2587
self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
2588
self.make_lock('repository')
2589
# we hard code the formats here because we are converting into
2590
# the meta format. The meta format upgrader can take this to a
2591
# future format within each component.
2592
self.put_format('repository', RepositoryFormat7())
2593
for entry in repository_names:
2594
self.move_entry('repository', entry)
2596
self.step('Upgrading branch ')
2597
self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
2598
self.make_lock('branch')
2599
self.put_format('branch', BzrBranchFormat5())
2600
branch_files = [('revision-history', True),
2601
('branch-name', True),
2603
for entry in branch_files:
2604
self.move_entry('branch', entry)
2606
checkout_files = [('pending-merges', True),
2607
('inventory', True),
2608
('stat-cache', False)]
2609
# If a mandatory checkout file is not present, the branch does not have
2610
# a functional checkout. Do not create a checkout in the converted
2612
for name, mandatory in checkout_files:
2613
if mandatory and name not in bzrcontents:
2614
has_checkout = False
2618
if not has_checkout:
2619
self.pb.note('No working tree.')
2620
# If some checkout files are there, we may as well get rid of them.
2621
for name, mandatory in checkout_files:
2622
if name in bzrcontents:
2623
self.bzrdir.transport.delete(name)
2625
from bzrlib.workingtree import WorkingTreeFormat3
2626
self.step('Upgrading working tree')
2627
self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
2628
self.make_lock('checkout')
2630
'checkout', WorkingTreeFormat3())
2631
self.bzrdir.transport.delete_multi(
2632
self.garbage_inventories, self.pb)
2633
for entry in checkout_files:
2634
self.move_entry('checkout', entry)
2635
if last_revision is not None:
2636
self.bzrdir.transport.put_bytes(
2637
'checkout/last-revision', last_revision)
2638
self.bzrdir.transport.put_bytes(
2640
BzrDirMetaFormat1().get_format_string(),
2641
mode=self.file_mode)
2642
return BzrDir.open(self.bzrdir.root_transport.base)
2644
def make_lock(self, name):
2645
"""Make a lock for the new control dir name."""
2646
self.step('Make %s lock' % name)
2647
ld = lockdir.LockDir(self.bzrdir.transport,
2649
file_modebits=self.file_mode,
2650
dir_modebits=self.dir_mode)
2653
def move_entry(self, new_dir, entry):
2654
"""Move then entry name into new_dir."""
2656
mandatory = entry[1]
2657
self.step('Moving %s' % name)
2659
self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
2660
except errors.NoSuchFile:
2664
def put_format(self, dirname, format):
2665
self.bzrdir.transport.put_bytes('%s/format' % dirname,
2666
format.get_format_string(),
2670
class ConvertMetaToMeta(Converter):
2671
"""Converts the components of metadirs."""
2673
def __init__(self, target_format):
2674
"""Create a metadir to metadir converter.
2676
:param target_format: The final metadir format that is desired.
2678
self.target_format = target_format
2680
def convert(self, to_convert, pb):
2681
"""See Converter.convert()."""
2682
self.bzrdir = to_convert
2686
self.step('checking repository format')
2688
repo = self.bzrdir.open_repository()
2689
except errors.NoRepositoryPresent:
2692
if not isinstance(repo._format, self.target_format.repository_format.__class__):
2693
from bzrlib.repository import CopyConverter
2694
self.pb.note('starting repository conversion')
2695
converter = CopyConverter(self.target_format.repository_format)
2696
converter.convert(repo, pb)
2698
branch = self.bzrdir.open_branch()
2699
except errors.NotBranchError:
2702
# TODO: conversions of Branch and Tree should be done by
2703
# InterXFormat lookups/some sort of registry.
2704
# Avoid circular imports
2705
from bzrlib import branch as _mod_branch
2706
old = branch._format.__class__
2707
new = self.target_format.get_branch_format().__class__
2709
if (old == _mod_branch.BzrBranchFormat5 and
2710
new in (_mod_branch.BzrBranchFormat6,
2711
_mod_branch.BzrBranchFormat7)):
2712
branch_converter = _mod_branch.Converter5to6()
2713
elif (old == _mod_branch.BzrBranchFormat6 and
2714
new == _mod_branch.BzrBranchFormat7):
2715
branch_converter = _mod_branch.Converter6to7()
2717
raise errors.BadConversionTarget("No converter", new)
2718
branch_converter.convert(branch)
2719
branch = self.bzrdir.open_branch()
2720
old = branch._format.__class__
2722
tree = self.bzrdir.open_workingtree(recommend_upgrade=False)
2723
except (errors.NoWorkingTree, errors.NotLocalUrl):
2726
# TODO: conversions of Branch and Tree should be done by
2727
# InterXFormat lookups
2728
if (isinstance(tree, workingtree.WorkingTree3) and
2729
not isinstance(tree, workingtree_4.DirStateWorkingTree) and
2730
isinstance(self.target_format.workingtree_format,
2731
workingtree_4.DirStateWorkingTreeFormat)):
2732
workingtree_4.Converter3to4().convert(tree)
2733
if (isinstance(tree, workingtree_4.DirStateWorkingTree) and
2734
not isinstance(tree, workingtree_4.WorkingTree5) and
2735
isinstance(self.target_format.workingtree_format,
2736
workingtree_4.WorkingTreeFormat5)):
2737
workingtree_4.Converter4to5().convert(tree)
2741
# This is not in remote.py because it's small, and needs to be registered.
2742
# Putting it in remote.py creates a circular import problem.
2743
# we can make it a lazy object if the control formats is turned into something
2745
class RemoteBzrDirFormat(BzrDirMetaFormat1):
2746
"""Format representing bzrdirs accessed via a smart server"""
2749
BzrDirMetaFormat1.__init__(self)
2750
self._network_name = None
2752
def get_format_description(self):
2753
return 'bzr remote bzrdir'
2755
def get_format_string(self):
2756
raise NotImplementedError(self.get_format_string)
2758
def network_name(self):
2759
if self._network_name:
2760
return self._network_name
2762
raise AssertionError("No network name set.")
2765
def probe_transport(klass, transport):
2766
"""Return a RemoteBzrDirFormat object if it looks possible."""
2768
medium = transport.get_smart_medium()
2769
except (NotImplementedError, AttributeError,
2770
errors.TransportNotPossible, errors.NoSmartMedium,
2771
errors.SmartProtocolError):
2772
# no smart server, so not a branch for this format type.
2773
raise errors.NotBranchError(path=transport.base)
2775
# Decline to open it if the server doesn't support our required
2776
# version (3) so that the VFS-based transport will do it.
2777
if medium.should_probe():
2779
server_version = medium.protocol_version()
2780
except errors.SmartProtocolError:
2781
# Apparently there's no usable smart server there, even though
2782
# the medium supports the smart protocol.
2783
raise errors.NotBranchError(path=transport.base)
2784
if server_version != '2':
2785
raise errors.NotBranchError(path=transport.base)
2788
def initialize_on_transport(self, transport):
2790
# hand off the request to the smart server
2791
client_medium = transport.get_smart_medium()
2792
except errors.NoSmartMedium:
2793
# TODO: lookup the local format from a server hint.
2794
local_dir_format = BzrDirMetaFormat1()
2795
return local_dir_format.initialize_on_transport(transport)
2796
client = _SmartClient(client_medium)
2797
path = client.remote_path_from_transport(transport)
2798
response = client.call('BzrDirFormat.initialize', path)
2799
if response[0] != 'ok':
2800
raise errors.SmartProtocolError('unexpected response code %s' % (response,))
2801
format = RemoteBzrDirFormat()
2802
self._supply_sub_formats_to(format)
2803
return remote.RemoteBzrDir(transport, format)
2805
def _open(self, transport):
2806
return remote.RemoteBzrDir(transport, self)
2808
def __eq__(self, other):
2809
if not isinstance(other, RemoteBzrDirFormat):
2811
return self.get_format_description() == other.get_format_description()
2813
def __return_repository_format(self):
2814
# Always return a RemoteRepositoryFormat object, but if a specific bzr
2815
# repository format has been asked for, tell the RemoteRepositoryFormat
2816
# that it should use that for init() etc.
2817
result = remote.RemoteRepositoryFormat()
2818
custom_format = getattr(self, '_repository_format', None)
2820
# We will use the custom format to create repositories over the
2821
# wire; expose its details like rich_root_data for code to query
2822
if isinstance(custom_format, remote.RemoteRepositoryFormat):
2823
result._custom_format = custom_format._custom_format
2825
result._custom_format = custom_format
2826
result.rich_root_data = custom_format.rich_root_data
2829
def get_branch_format(self):
2830
result = BzrDirMetaFormat1.get_branch_format(self)
2831
if not isinstance(result, remote.RemoteBranchFormat):
2832
new_result = remote.RemoteBranchFormat()
2833
new_result._custom_format = result
2835
self.set_branch_format(new_result)
2839
repository_format = property(__return_repository_format,
2840
BzrDirMetaFormat1._set_repository_format) #.im_func)
2843
BzrDirFormat.register_control_server_format(RemoteBzrDirFormat)
2846
class BzrDirFormatInfo(object):
2848
def __init__(self, native, deprecated, hidden, experimental):
2849
self.deprecated = deprecated
2850
self.native = native
2851
self.hidden = hidden
2852
self.experimental = experimental
2855
class BzrDirFormatRegistry(registry.Registry):
2856
"""Registry of user-selectable BzrDir subformats.
2858
Differs from BzrDirFormat._control_formats in that it provides sub-formats,
2859
e.g. BzrDirMeta1 with weave repository. Also, it's more user-oriented.
2863
"""Create a BzrDirFormatRegistry."""
2864
self._aliases = set()
2865
self._registration_order = list()
2866
super(BzrDirFormatRegistry, self).__init__()
2869
"""Return a set of the format names which are aliases."""
2870
return frozenset(self._aliases)
2872
def register_metadir(self, key,
2873
repository_format, help, native=True, deprecated=False,
2879
"""Register a metadir subformat.
2881
These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
2882
by the Repository/Branch/WorkingTreeformats.
2884
:param repository_format: The fully-qualified repository format class
2886
:param branch_format: Fully-qualified branch format class name as
2888
:param tree_format: Fully-qualified tree format class name as
2891
# This should be expanded to support setting WorkingTree and Branch
2892
# formats, once BzrDirMetaFormat1 supports that.
2893
def _load(full_name):
2894
mod_name, factory_name = full_name.rsplit('.', 1)
2896
mod = __import__(mod_name, globals(), locals(),
2898
except ImportError, e:
2899
raise ImportError('failed to load %s: %s' % (full_name, e))
2901
factory = getattr(mod, factory_name)
2902
except AttributeError:
2903
raise AttributeError('no factory %s in module %r'
2908
bd = BzrDirMetaFormat1()
2909
if branch_format is not None:
2910
bd.set_branch_format(_load(branch_format))
2911
if tree_format is not None:
2912
bd.workingtree_format = _load(tree_format)
2913
if repository_format is not None:
2914
bd.repository_format = _load(repository_format)
2916
self.register(key, helper, help, native, deprecated, hidden,
2917
experimental, alias)
2919
def register(self, key, factory, help, native=True, deprecated=False,
2920
hidden=False, experimental=False, alias=False):
2921
"""Register a BzrDirFormat factory.
2923
The factory must be a callable that takes one parameter: the key.
2924
It must produce an instance of the BzrDirFormat when called.
2926
This function mainly exists to prevent the info object from being
2929
registry.Registry.register(self, key, factory, help,
2930
BzrDirFormatInfo(native, deprecated, hidden, experimental))
2932
self._aliases.add(key)
2933
self._registration_order.append(key)
2935
def register_lazy(self, key, module_name, member_name, help, native=True,
2936
deprecated=False, hidden=False, experimental=False, alias=False):
2937
registry.Registry.register_lazy(self, key, module_name, member_name,
2938
help, BzrDirFormatInfo(native, deprecated, hidden, experimental))
2940
self._aliases.add(key)
2941
self._registration_order.append(key)
2943
def set_default(self, key):
2944
"""Set the 'default' key to be a clone of the supplied key.
2946
This method must be called once and only once.
2948
registry.Registry.register(self, 'default', self.get(key),
2949
self.get_help(key), info=self.get_info(key))
2950
self._aliases.add('default')
2952
def set_default_repository(self, key):
2953
"""Set the FormatRegistry default and Repository default.
2955
This is a transitional method while Repository.set_default_format
2958
if 'default' in self:
2959
self.remove('default')
2960
self.set_default(key)
2961
format = self.get('default')()
2963
def make_bzrdir(self, key):
2964
return self.get(key)()
2966
def help_topic(self, topic):
2968
default_realkey = None
2969
default_help = self.get_help('default')
2971
for key in self._registration_order:
2972
if key == 'default':
2974
help = self.get_help(key)
2975
if help == default_help:
2976
default_realkey = key
2978
help_pairs.append((key, help))
2980
def wrapped(key, help, info):
2982
help = '(native) ' + help
2983
return ':%s:\n%s\n\n' % (key,
2984
textwrap.fill(help, initial_indent=' ',
2985
subsequent_indent=' '))
2986
if default_realkey is not None:
2987
output += wrapped(default_realkey, '(default) %s' % default_help,
2988
self.get_info('default'))
2989
deprecated_pairs = []
2990
experimental_pairs = []
2991
for key, help in help_pairs:
2992
info = self.get_info(key)
2995
elif info.deprecated:
2996
deprecated_pairs.append((key, help))
2997
elif info.experimental:
2998
experimental_pairs.append((key, help))
3000
output += wrapped(key, help, info)
3001
output += "\nSee ``bzr help formats`` for more about storage formats."
3003
if len(experimental_pairs) > 0:
3004
other_output += "Experimental formats are shown below.\n\n"
3005
for key, help in experimental_pairs:
3006
info = self.get_info(key)
3007
other_output += wrapped(key, help, info)
3010
"No experimental formats are available.\n\n"
3011
if len(deprecated_pairs) > 0:
3012
other_output += "\nDeprecated formats are shown below.\n\n"
3013
for key, help in deprecated_pairs:
3014
info = self.get_info(key)
3015
other_output += wrapped(key, help, info)
3018
"\nNo deprecated formats are available.\n\n"
3020
"\nSee ``bzr help formats`` for more about storage formats."
3022
if topic == 'other-formats':
3028
class RepositoryAcquisitionPolicy(object):
3029
"""Abstract base class for repository acquisition policies.
3031
A repository acquisition policy decides how a BzrDir acquires a repository
3032
for a branch that is being created. The most basic policy decision is
3033
whether to create a new repository or use an existing one.
3035
def __init__(self, stack_on, stack_on_pwd, require_stacking):
3038
:param stack_on: A location to stack on
3039
:param stack_on_pwd: If stack_on is relative, the location it is
3041
:param require_stacking: If True, it is a failure to not stack.
3043
self._stack_on = stack_on
3044
self._stack_on_pwd = stack_on_pwd
3045
self._require_stacking = require_stacking
3047
def configure_branch(self, branch):
3048
"""Apply any configuration data from this policy to the branch.
3050
Default implementation sets repository stacking.
3052
if self._stack_on is None:
3054
if self._stack_on_pwd is None:
3055
stack_on = self._stack_on
3058
stack_on = urlutils.rebase_url(self._stack_on,
3060
branch.bzrdir.root_transport.base)
3061
except errors.InvalidRebaseURLs:
3062
stack_on = self._get_full_stack_on()
3064
branch.set_stacked_on_url(stack_on)
3065
except errors.UnstackableBranchFormat:
3066
if self._require_stacking:
3069
def _get_full_stack_on(self):
3070
"""Get a fully-qualified URL for the stack_on location."""
3071
if self._stack_on is None:
3073
if self._stack_on_pwd is None:
3074
return self._stack_on
3076
return urlutils.join(self._stack_on_pwd, self._stack_on)
3078
def _add_fallback(self, repository, possible_transports=None):
3079
"""Add a fallback to the supplied repository, if stacking is set."""
3080
stack_on = self._get_full_stack_on()
3081
if stack_on is None:
3083
stacked_dir = BzrDir.open(stack_on,
3084
possible_transports=possible_transports)
3086
stacked_repo = stacked_dir.open_branch().repository
3087
except errors.NotBranchError:
3088
stacked_repo = stacked_dir.open_repository()
3090
repository.add_fallback_repository(stacked_repo)
3091
except errors.UnstackableRepositoryFormat:
3092
if self._require_stacking:
3095
self._require_stacking = True
3097
def acquire_repository(self, make_working_trees=None, shared=False):
3098
"""Acquire a repository for this bzrdir.
3100
Implementations may create a new repository or use a pre-exising
3102
:param make_working_trees: If creating a repository, set
3103
make_working_trees to this value (if non-None)
3104
:param shared: If creating a repository, make it shared if True
3105
:return: A repository, is_new_flag (True if the repository was
3108
raise NotImplemented(RepositoryAcquisitionPolicy.acquire_repository)
3111
class CreateRepository(RepositoryAcquisitionPolicy):
3112
"""A policy of creating a new repository"""
3114
def __init__(self, bzrdir, stack_on=None, stack_on_pwd=None,
3115
require_stacking=False):
3118
:param bzrdir: The bzrdir to create the repository on.
3119
:param stack_on: A location to stack on
3120
:param stack_on_pwd: If stack_on is relative, the location it is
3123
RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
3125
self._bzrdir = bzrdir
3127
def acquire_repository(self, make_working_trees=None, shared=False):
3128
"""Implementation of RepositoryAcquisitionPolicy.acquire_repository
3130
Creates the desired repository in the bzrdir we already have.
3132
repository = self._bzrdir.create_repository(shared=shared)
3133
self._add_fallback(repository,
3134
possible_transports=[self._bzrdir.transport])
3135
if make_working_trees is not None:
3136
repository.set_make_working_trees(make_working_trees)
3137
return repository, True
3140
class UseExistingRepository(RepositoryAcquisitionPolicy):
3141
"""A policy of reusing an existing repository"""
3143
def __init__(self, repository, stack_on=None, stack_on_pwd=None,
3144
require_stacking=False):
3147
:param repository: The repository to use.
3148
:param stack_on: A location to stack on
3149
:param stack_on_pwd: If stack_on is relative, the location it is
3152
RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
3154
self._repository = repository
3156
def acquire_repository(self, make_working_trees=None, shared=False):
3157
"""Implementation of RepositoryAcquisitionPolicy.acquire_repository
3159
Returns an existing repository to use.
3161
self._add_fallback(self._repository,
3162
possible_transports=[self._repository.bzrdir.transport])
3163
return self._repository, False
3166
# Please register new formats after old formats so that formats
3167
# appear in chronological order and format descriptions can build
3169
format_registry = BzrDirFormatRegistry()
3170
# The pre-0.8 formats have their repository format network name registered in
3171
# repository.py. MetaDir formats have their repository format network name
3172
# inferred from their disk format string.
3173
format_registry.register('weave', BzrDirFormat6,
3174
'Pre-0.8 format. Slower than knit and does not'
3175
' support checkouts or shared repositories.',
3177
format_registry.register_metadir('metaweave',
3178
'bzrlib.repofmt.weaverepo.RepositoryFormat7',
3179
'Transitional format in 0.8. Slower than knit.',
3180
branch_format='bzrlib.branch.BzrBranchFormat5',
3181
tree_format='bzrlib.workingtree.WorkingTreeFormat3',
3183
format_registry.register_metadir('knit',
3184
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3185
'Format using knits. Recommended for interoperation with bzr <= 0.14.',
3186
branch_format='bzrlib.branch.BzrBranchFormat5',
3187
tree_format='bzrlib.workingtree.WorkingTreeFormat3',
3189
format_registry.register_metadir('dirstate',
3190
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3191
help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
3192
'above when accessed over the network.',
3193
branch_format='bzrlib.branch.BzrBranchFormat5',
3194
# this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
3195
# directly from workingtree_4 triggers a circular import.
3196
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3198
format_registry.register_metadir('dirstate-tags',
3199
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3200
help='New in 0.15: Fast local operations and improved scaling for '
3201
'network operations. Additionally adds support for tags.'
3202
' Incompatible with bzr < 0.15.',
3203
branch_format='bzrlib.branch.BzrBranchFormat6',
3204
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3206
format_registry.register_metadir('rich-root',
3207
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
3208
help='New in 1.0. Better handling of tree roots. Incompatible with'
3210
branch_format='bzrlib.branch.BzrBranchFormat6',
3211
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3213
format_registry.register_metadir('dirstate-with-subtree',
3214
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
3215
help='New in 0.15: Fast local operations and improved scaling for '
3216
'network operations. Additionally adds support for versioning nested '
3217
'bzr branches. Incompatible with bzr < 0.15.',
3218
branch_format='bzrlib.branch.BzrBranchFormat6',
3219
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3223
format_registry.register_metadir('pack-0.92',
3224
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
3225
help='New in 0.92: Pack-based format with data compatible with '
3226
'dirstate-tags format repositories. Interoperates with '
3227
'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
3228
'Previously called knitpack-experimental. '
3229
'For more information, see '
3230
'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
3231
branch_format='bzrlib.branch.BzrBranchFormat6',
3232
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3234
format_registry.register_metadir('pack-0.92-subtree',
3235
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
3236
help='New in 0.92: Pack-based format with data compatible with '
3237
'dirstate-with-subtree format repositories. Interoperates with '
3238
'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
3239
'Previously called knitpack-experimental. '
3240
'For more information, see '
3241
'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
3242
branch_format='bzrlib.branch.BzrBranchFormat6',
3243
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3247
format_registry.register_metadir('rich-root-pack',
3248
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
3249
help='New in 1.0: A variant of pack-0.92 that supports rich-root data '
3250
'(needed for bzr-svn).',
3251
branch_format='bzrlib.branch.BzrBranchFormat6',
3252
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3254
format_registry.register_metadir('1.6',
3255
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5',
3256
help='A format that allows a branch to indicate that there is another '
3257
'(stacked) repository that should be used to access data that is '
3258
'not present locally.',
3259
branch_format='bzrlib.branch.BzrBranchFormat7',
3260
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3262
format_registry.register_metadir('1.6.1-rich-root',
3263
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5RichRoot',
3264
help='A variant of 1.6 that supports rich-root data '
3265
'(needed for bzr-svn).',
3266
branch_format='bzrlib.branch.BzrBranchFormat7',
3267
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3269
format_registry.register_metadir('1.9',
3270
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
3271
help='A repository format using B+tree indexes. These indexes '
3272
'are smaller in size, have smarter caching and provide faster '
3273
'performance for most operations.',
3274
branch_format='bzrlib.branch.BzrBranchFormat7',
3275
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3277
format_registry.register_metadir('1.9-rich-root',
3278
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
3279
help='A variant of 1.9 that supports rich-root data '
3280
'(needed for bzr-svn).',
3281
branch_format='bzrlib.branch.BzrBranchFormat7',
3282
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3284
format_registry.register_metadir('development-wt5',
3285
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
3286
help='A working-tree format that supports views and content filtering.',
3287
branch_format='bzrlib.branch.BzrBranchFormat7',
3288
tree_format='bzrlib.workingtree.WorkingTreeFormat5',
3291
format_registry.register_metadir('development-wt5-rich-root',
3292
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
3293
help='A variant of development-wt5 that supports rich-root data '
3294
'(needed for bzr-svn).',
3295
branch_format='bzrlib.branch.BzrBranchFormat7',
3296
tree_format='bzrlib.workingtree.WorkingTreeFormat5',
3299
# The following two formats should always just be aliases.
3300
format_registry.register_metadir('development',
3301
'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2',
3302
help='Current development format. Can convert data to and from pack-0.92 '
3303
'(and anything compatible with pack-0.92) format repositories. '
3304
'Repositories and branches in this format can only be read by bzr.dev. '
3306
'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3308
branch_format='bzrlib.branch.BzrBranchFormat7',
3309
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3313
format_registry.register_metadir('development-subtree',
3314
'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
3315
help='Current development format, subtree variant. Can convert data to and '
3316
'from pack-0.92-subtree (and anything compatible with '
3317
'pack-0.92-subtree) format repositories. Repositories and branches in '
3318
'this format can only be read by bzr.dev. Please read '
3319
'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3321
branch_format='bzrlib.branch.BzrBranchFormat7',
3322
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3326
# And the development formats above will have aliased one of the following:
3327
format_registry.register_metadir('development2',
3328
'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2',
3329
help='1.6.1 with B+Tree based index. '
3331
'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3333
branch_format='bzrlib.branch.BzrBranchFormat7',
3334
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3338
format_registry.register_metadir('development2-subtree',
3339
'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
3340
help='1.6.1-subtree with B+Tree based index. '
3342
'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
3344
branch_format='bzrlib.branch.BzrBranchFormat7',
3345
tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3349
# The current format that is made on 'bzr init'.
3350
format_registry.set_default('pack-0.92')