1
# Copyright (C) 2005 Canonical Ltd
1
# Copyright (C) 2005-2012 Canonical Ltd
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
11
# GNU General Public License for more details.
13
13
# You should have received a copy of the GNU General Public License
14
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
22
from bzrlib.trace import mutter, note
23
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
25
sha_file, appendpath, file_kind
26
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId
28
from bzrlib.textui import show_status
29
from bzrlib.revision import Revision
30
from bzrlib.xml import unpack_xml
31
from bzrlib.delta import compare_trees
32
from bzrlib.tree import EmptyTree, RevisionTree
34
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
35
## TODO: Maybe include checks for common corruption of newlines, etc?
38
# TODO: Some operations like log might retrieve the same revisions
39
# repeatedly to calculate deltas. We could perhaps have a weakref
40
# cache in memory to make this faster.
43
def find_branch(f, **args):
44
if f and (f.startswith('http://') or f.startswith('https://')):
46
return remotebranch.RemoteBranch(f, **args)
48
return Branch(f, **args)
51
def find_cached_branch(f, cache_root, **args):
52
from remotebranch import RemoteBranch
53
br = find_branch(f, **args)
54
def cacheify(br, store_name):
55
from meta_store import CachedStore
56
cache_path = os.path.join(cache_root, store_name)
58
new_store = CachedStore(getattr(br, store_name), cache_path)
59
setattr(br, store_name, new_store)
61
if isinstance(br, RemoteBranch):
62
cacheify(br, 'inventory_store')
63
cacheify(br, 'text_store')
64
cacheify(br, 'revision_store')
68
def _relpath(base, path):
69
"""Return path relative to base, or raise exception.
71
The path may be either an absolute path or a path relative to the
72
current working directory.
74
Lifted out of Branch.relpath for ease of testing.
76
os.path.commonprefix (python2.4) has a bad bug that it works just
77
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
78
avoids that problem."""
79
rp = os.path.abspath(path)
83
while len(head) >= len(base):
86
head, tail = os.path.split(head)
90
from errors import NotBranchError
91
raise NotBranchError("path %r is not within branch %r" % (rp, base))
96
def find_branch_root(f=None):
97
"""Find the branch root enclosing f, or pwd.
99
f may be a filename or a URL.
101
It is not necessary that f exists.
103
Basically we keep looking up until we find the control directory or
104
run into the root."""
107
elif hasattr(os.path, 'realpath'):
108
f = os.path.realpath(f)
110
f = os.path.abspath(f)
111
if not os.path.exists(f):
112
raise BzrError('%r does not exist' % f)
118
if os.path.exists(os.path.join(f, bzrlib.BZRDIR)):
120
head, tail = os.path.split(f)
122
# reached the root, whatever that may be
123
raise BzrError('%r is not in a branch' % orig_f)
126
class DivergedBranches(Exception):
127
def __init__(self, branch1, branch2):
128
self.branch1 = branch1
129
self.branch2 = branch2
130
Exception.__init__(self, "These branches have diverged.")
133
######################################################################
136
class Branch(object):
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
from __future__ import absolute_import
21
from cStringIO import StringIO
23
from bzrlib.lazy_import import lazy_import
24
lazy_import(globals(), """
31
config as _mod_config,
40
revision as _mod_revision,
49
from bzrlib.i18n import gettext, ngettext
52
# Explicitly import bzrlib.bzrdir so that the BzrProber
53
# is guaranteed to be registered.
60
from bzrlib.decorators import (
65
from bzrlib.hooks import Hooks
66
from bzrlib.inter import InterObject
67
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
68
from bzrlib import registry
69
from bzrlib.symbol_versioning import (
73
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
76
class Branch(controldir.ControlComponent):
137
77
"""Branch holding a history of revisions.
140
Base directory of the branch.
146
If _lock_mode is true, a positive count of the number of times the
150
Lock object from bzrlib.lock.
80
Base directory/url of the branch; using control_url and
81
control_transport is more standardized.
82
:ivar hooks: An instance of BranchHooks.
83
:ivar _master_branch_cache: cached result of get_master_branch, see
86
# this is really an instance variable - FIXME move it there
157
# Map some sort of prefix into a namespace
158
# stuff like "revno:10", "revid:", etc.
159
# This should match a prefix with a function which accepts
160
REVISION_NAMESPACES = {}
162
def __init__(self, base, init=False, find_root=True):
163
"""Create new branch object at a particular location.
165
base -- Base directory for the branch.
167
init -- If True, create new control files in a previously
168
unversioned directory. If False, the branch must already
171
find_root -- If true and init is false, find the root of the
172
existing branch containing base.
174
In the test suite, creation of new trees is tested using the
175
`ScratchBranch` class.
177
from bzrlib.store import ImmutableStore
179
self.base = os.path.realpath(base)
182
self.base = find_branch_root(base)
184
self.base = os.path.realpath(base)
185
if not isdir(self.controlfilename('.')):
186
from errors import NotBranchError
187
raise NotBranchError("not a bzr branch: %s" % quotefn(base),
188
['use "bzr init" to initialize a new working tree',
189
'current bzr can only operate from top-of-tree'])
192
self.text_store = ImmutableStore(self.controlfilename('text-store'))
193
self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
194
self.inventory_store = ImmutableStore(self.controlfilename('inventory-store'))
198
return '%s(%r)' % (self.__class__.__name__, self.base)
205
if self._lock_mode or self._lock:
206
from warnings import warn
207
warn("branch %r was not explicitly unlocked" % self)
212
def lock_write(self):
214
if self._lock_mode != 'w':
215
from errors import LockError
216
raise LockError("can't upgrade to a write lock from %r" %
218
self._lock_count += 1
220
from bzrlib.lock import WriteLock
222
self._lock = WriteLock(self.controlfilename('branch-lock'))
223
self._lock_mode = 'w'
91
def control_transport(self):
92
return self._transport
95
def user_transport(self):
96
return self.bzrdir.user_transport
98
def __init__(self, possible_transports=None):
99
self.tags = self._format.make_tags(self)
100
self._revision_history_cache = None
101
self._revision_id_to_revno_cache = None
102
self._partial_revision_id_to_revno_cache = {}
103
self._partial_revision_history_cache = []
104
self._tags_bytes = None
105
self._last_revision_info_cache = None
106
self._master_branch_cache = None
107
self._merge_sorted_revisions_cache = None
108
self._open_hook(possible_transports)
109
hooks = Branch.hooks['open']
113
def _open_hook(self, possible_transports):
114
"""Called by init to allow simpler extension of the base class."""
116
def _activate_fallback_location(self, url, possible_transports):
117
"""Activate the branch/repository from url as a fallback repository."""
118
for existing_fallback_repo in self.repository._fallback_repositories:
119
if existing_fallback_repo.user_url == url:
120
# This fallback is already configured. This probably only
121
# happens because ControlDir.sprout is a horrible mess. To avoid
122
# confusing _unstack we don't add this a second time.
123
mutter('duplicate activation of fallback %r on %r', url, self)
125
repo = self._get_fallback_repository(url, possible_transports)
126
if repo.has_same_location(self.repository):
127
raise errors.UnstackableLocationError(self.user_url, url)
128
self.repository.add_fallback_repository(repo)
130
def break_lock(self):
131
"""Break a lock if one is present from another instance.
133
Uses the ui factory to ask for confirmation if the lock may be from
136
This will probe the repository for its lock as well.
138
self.control_files.break_lock()
139
self.repository.break_lock()
140
master = self.get_master_branch()
141
if master is not None:
144
def _check_stackable_repo(self):
145
if not self.repository._format.supports_external_lookups:
146
raise errors.UnstackableRepositoryFormat(self.repository._format,
147
self.repository.base)
149
def _extend_partial_history(self, stop_index=None, stop_revision=None):
150
"""Extend the partial history to include a given index
152
If a stop_index is supplied, stop when that index has been reached.
153
If a stop_revision is supplied, stop when that revision is
154
encountered. Otherwise, stop when the beginning of history is
157
:param stop_index: The index which should be present. When it is
158
present, history extension will stop.
159
:param stop_revision: The revision id which should be present. When
160
it is encountered, history extension will stop.
162
if len(self._partial_revision_history_cache) == 0:
163
self._partial_revision_history_cache = [self.last_revision()]
164
repository._iter_for_revno(
165
self.repository, self._partial_revision_history_cache,
166
stop_index=stop_index, stop_revision=stop_revision)
167
if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
168
self._partial_revision_history_cache.pop()
170
def _get_check_refs(self):
171
"""Get the references needed for check().
175
revid = self.last_revision()
176
return [('revision-existence', revid), ('lefthand-distance', revid)]
179
def open(base, _unsupported=False, possible_transports=None):
180
"""Open the branch rooted at base.
182
For instance, if the branch is at URL/.bzr/branch,
183
Branch.open(URL) -> a Branch instance.
185
control = controldir.ControlDir.open(base,
186
possible_transports=possible_transports, _unsupported=_unsupported)
187
return control.open_branch(unsupported=_unsupported,
188
possible_transports=possible_transports)
191
def open_from_transport(transport, name=None, _unsupported=False,
192
possible_transports=None):
193
"""Open the branch rooted at transport"""
194
control = controldir.ControlDir.open_from_transport(transport, _unsupported)
195
return control.open_branch(name=name, unsupported=_unsupported,
196
possible_transports=possible_transports)
199
def open_containing(url, possible_transports=None):
200
"""Open an existing branch which contains url.
202
This probes for a branch at url, and searches upwards from there.
204
Basically we keep looking up until we find the control directory or
205
run into the root. If there isn't one, raises NotBranchError.
206
If there is one and it is either an unrecognised format or an unsupported
207
format, UnknownFormatError or UnsupportedFormatError are raised.
208
If there is one, it is returned, along with the unused portion of url.
210
control, relpath = controldir.ControlDir.open_containing(url,
212
branch = control.open_branch(possible_transports=possible_transports)
213
return (branch, relpath)
215
def _push_should_merge_tags(self):
216
"""Should _basic_push merge this branch's tags into the target?
218
The default implementation returns False if this branch has no tags,
219
and True the rest of the time. Subclasses may override this.
221
return self.supports_tags() and self.tags.get_tag_dict()
223
def get_config(self):
224
"""Get a bzrlib.config.BranchConfig for this Branch.
226
This can then be used to get and set configuration options for the
229
:return: A bzrlib.config.BranchConfig.
231
return _mod_config.BranchConfig(self)
233
def get_config_stack(self):
234
"""Get a bzrlib.config.BranchStack for this Branch.
236
This can then be used to get and set configuration options for the
239
:return: A bzrlib.config.BranchStack.
241
return _mod_config.BranchStack(self)
243
def _get_config(self):
244
"""Get the concrete config for just the config in this branch.
246
This is not intended for client use; see Branch.get_config for the
251
:return: An object supporting get_option and set_option.
253
raise NotImplementedError(self._get_config)
255
def _get_uncommitted(self):
256
"""Return a serialized TreeTransform for uncommitted changes.
258
:return: a file-like object containing a serialized TreeTransform or
259
None if no uncommitted changes are stored.
261
raise NotImplementedError(self._get_uncommitted)
263
def _put_uncommitted(self, transform):
264
"""Store a serialized TreeTransform for uncommitted changes.
266
:param input: a file-like object.
268
raise NotImplementedError(self._put_uncommitted)
270
def has_stored_uncommitted(self):
271
"""If true, the branch has stored, uncommitted changes in it."""
272
return self._get_uncommitted() is not None
274
def store_uncommitted(self, creator, message=None):
275
if self.has_stored_uncommitted():
276
raise errors.ChangesAlreadyStored
277
transform = StringIO()
278
creator.write_shelf(transform, message)
280
self._put_uncommitted(transform)
282
def get_uncommitted_data(self):
283
transform = self._get_uncommitted()
284
if transform is None:
286
records = shelf.Unshelver.iter_records(transform)
287
metadata = shelf.Unshelver.parse_metadata(records)
288
base_revision_id = metadata['revision_id']
289
return base_revision_id, records
291
def _get_fallback_repository(self, url, possible_transports):
292
"""Get the repository we fallback to at url."""
293
url = urlutils.join(self.base, url)
294
a_branch = Branch.open(url, possible_transports=possible_transports)
295
return a_branch.repository
298
def _get_tags_bytes(self):
299
"""Get the bytes of a serialised tags dict.
301
Note that not all branches support tags, nor do all use the same tags
302
logic: this method is specific to BasicTags. Other tag implementations
303
may use the same method name and behave differently, safely, because
304
of the double-dispatch via
305
format.make_tags->tags_instance->get_tags_dict.
307
:return: The bytes of the tags file.
308
:seealso: Branch._set_tags_bytes.
310
if self._tags_bytes is None:
311
self._tags_bytes = self._transport.get_bytes('tags')
312
return self._tags_bytes
314
def _get_nick(self, local=False, possible_transports=None):
315
config = self.get_config()
316
# explicit overrides master, but don't look for master if local is True
317
if not local and not config.has_explicit_nickname():
319
master = self.get_master_branch(possible_transports)
320
if master and self.user_url == master.user_url:
321
raise errors.RecursiveBind(self.user_url)
322
if master is not None:
323
# return the master branch value
325
except errors.RecursiveBind, e:
327
except errors.BzrError, e:
328
# Silently fall back to local implicit nick if the master is
330
mutter("Could not connect to bound branch, "
331
"falling back to local nick.\n " + str(e))
332
return config.get_nickname()
334
def _set_nick(self, nick):
335
self.get_config().set_user_option('nickname', nick, warn_masked=True)
337
nick = property(_get_nick, _set_nick)
340
raise NotImplementedError(self.is_locked)
342
def _lefthand_history(self, revision_id, last_rev=None,
344
if 'evil' in debug.debug_flags:
345
mutter_callsite(4, "_lefthand_history scales with history.")
346
# stop_revision must be a descendant of last_revision
347
graph = self.repository.get_graph()
348
if last_rev is not None:
349
if not graph.is_ancestor(last_rev, revision_id):
350
# our previous tip is not merged into stop_revision
351
raise errors.DivergedBranches(self, other_branch)
352
# make a new revision history from the graph
353
parents_map = graph.get_parent_map([revision_id])
354
if revision_id not in parents_map:
355
raise errors.NoSuchRevision(self, revision_id)
356
current_rev_id = revision_id
358
check_not_reserved_id = _mod_revision.check_not_reserved_id
359
# Do not include ghosts or graph origin in revision_history
360
while (current_rev_id in parents_map and
361
len(parents_map[current_rev_id]) > 0):
362
check_not_reserved_id(current_rev_id)
363
new_history.append(current_rev_id)
364
current_rev_id = parents_map[current_rev_id][0]
365
parents_map = graph.get_parent_map([current_rev_id])
366
new_history.reverse()
369
def lock_write(self, token=None):
370
"""Lock the branch for write operations.
372
:param token: A token to permit reacquiring a previously held and
374
:return: A BranchWriteLockResult.
376
raise NotImplementedError(self.lock_write)
228
378
def lock_read(self):
230
assert self._lock_mode in ('r', 'w'), \
231
"invalid lock mode %r" % self._lock_mode
232
self._lock_count += 1
234
from bzrlib.lock import ReadLock
236
self._lock = ReadLock(self.controlfilename('branch-lock'))
237
self._lock_mode = 'r'
379
"""Lock the branch for read operations.
381
:return: A bzrlib.lock.LogicalLockResult.
383
raise NotImplementedError(self.lock_read)
242
385
def unlock(self):
243
if not self._lock_mode:
244
from errors import LockError
245
raise LockError('branch %r is not locked' % (self))
247
if self._lock_count > 1:
248
self._lock_count -= 1
252
self._lock_mode = self._lock_count = None
255
def abspath(self, name):
256
"""Return absolute filename for something in the branch"""
257
return os.path.join(self.base, name)
260
def relpath(self, path):
261
"""Return path relative to this branch of something inside it.
263
Raises an error if path is not in this branch."""
264
return _relpath(self.base, path)
267
def controlfilename(self, file_or_path):
268
"""Return location relative to branch."""
269
if isinstance(file_or_path, basestring):
270
file_or_path = [file_or_path]
271
return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
274
def controlfile(self, file_or_path, mode='r'):
275
"""Open a control file for this branch.
277
There are two classes of file in the control directory: text
278
and binary. binary files are untranslated byte streams. Text
279
control files are stored with Unix newlines and in UTF-8, even
280
if the platform or locale defaults are different.
282
Controlfiles should almost never be opened in write mode but
283
rather should be atomically copied and replaced using atomicfile.
286
fn = self.controlfilename(file_or_path)
288
if mode == 'rb' or mode == 'wb':
289
return file(fn, mode)
290
elif mode == 'r' or mode == 'w':
291
# open in binary mode anyhow so there's no newline translation;
292
# codecs uses line buffering by default; don't want that.
294
return codecs.open(fn, mode + 'b', 'utf-8',
297
raise BzrError("invalid controlfile mode %r" % mode)
301
def _make_control(self):
302
from bzrlib.inventory import Inventory
303
from bzrlib.xml import pack_xml
305
os.mkdir(self.controlfilename([]))
306
self.controlfile('README', 'w').write(
307
"This is a Bazaar-NG control directory.\n"
308
"Do not change any files in this directory.\n")
309
self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT)
310
for d in ('text-store', 'inventory-store', 'revision-store'):
311
os.mkdir(self.controlfilename(d))
312
for f in ('revision-history', 'merged-patches',
313
'pending-merged-patches', 'branch-name',
316
self.controlfile(f, 'w').write('')
317
mutter('created control directory in ' + self.base)
319
# if we want per-tree root ids then this is the place to set
320
# them; they're not needed for now and so ommitted for
322
pack_xml(Inventory(), self.controlfile('inventory','w'))
325
def _check_format(self):
326
"""Check this branch format is supported.
328
The current tool only supports the current unstable format.
330
In the future, we might need different in-memory Branch
331
classes to support downlevel branches. But not yet.
333
# This ignores newlines so that we can open branches created
334
# on Windows from Linux and so on. I think it might be better
335
# to always make all internal files in unix format.
336
fmt = self.controlfile('branch-format', 'r').read()
337
fmt.replace('\r\n', '')
338
if fmt != BZR_BRANCH_FORMAT:
339
raise BzrError('sorry, branch format %r not supported' % fmt,
340
['use a different bzr version',
341
'or remove the .bzr directory and "bzr init" again'])
343
def get_root_id(self):
344
"""Return the id of this branches root"""
345
inv = self.read_working_inventory()
346
return inv.root.file_id
348
def set_root_id(self, file_id):
349
inv = self.read_working_inventory()
350
orig_root_id = inv.root.file_id
351
del inv._byid[inv.root.file_id]
352
inv.root.file_id = file_id
353
inv._byid[inv.root.file_id] = inv.root
356
if entry.parent_id in (None, orig_root_id):
357
entry.parent_id = inv.root.file_id
358
self._write_inventory(inv)
360
def read_working_inventory(self):
361
"""Read the working inventory."""
362
from bzrlib.inventory import Inventory
363
from bzrlib.xml import unpack_xml
364
from time import time
368
# ElementTree does its own conversion from UTF-8, so open in
370
inv = unpack_xml(Inventory,
371
self.controlfile('inventory', 'rb'))
372
mutter("loaded inventory of %d items in %f"
373
% (len(inv), time() - before))
379
def _write_inventory(self, inv):
380
"""Update the working inventory.
382
That is to say, the inventory describing changes underway, that
383
will be committed to the next revision.
385
from bzrlib.atomicfile import AtomicFile
386
from bzrlib.xml import pack_xml
390
f = AtomicFile(self.controlfilename('inventory'), 'wb')
399
mutter('wrote working inventory')
402
inventory = property(read_working_inventory, _write_inventory, None,
403
"""Inventory for the working copy.""")
406
def add(self, files, verbose=False, ids=None):
407
"""Make files versioned.
409
Note that the command line normally calls smart_add instead.
411
This puts the files in the Added state, so that they will be
412
recorded by the next commit.
415
List of paths to add, relative to the base of the tree.
418
If set, use these instead of automatically generated ids.
419
Must be the same length as the list of files, but may
420
contain None for ids that are to be autogenerated.
422
TODO: Perhaps have an option to add the ids even if the files do
425
TODO: Perhaps return the ids of the files? But then again it
426
is easy to retrieve them if they're needed.
428
TODO: Adding a directory should optionally recurse down and
429
add all non-ignored children. Perhaps do that in a
432
# TODO: Re-adding a file that is removed in the working copy
433
# should probably put it back with the previous ID.
434
if isinstance(files, basestring):
435
assert(ids is None or isinstance(ids, basestring))
441
ids = [None] * len(files)
443
assert(len(ids) == len(files))
447
inv = self.read_working_inventory()
448
for f,file_id in zip(files, ids):
449
if is_control_file(f):
450
raise BzrError("cannot add control file %s" % quotefn(f))
455
raise BzrError("cannot add top-level %r" % f)
457
fullpath = os.path.normpath(self.abspath(f))
460
kind = file_kind(fullpath)
462
# maybe something better?
463
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
465
if kind != 'file' and kind != 'directory':
466
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
469
file_id = gen_file_id(f)
470
inv.add_path(f, kind=kind, file_id=file_id)
473
print 'added', quotefn(f)
475
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
477
self._write_inventory(inv)
482
def print_file(self, file, revno):
483
"""Print `file` to stdout."""
486
tree = self.revision_tree(self.lookup_revision(revno))
487
# use inventory as it was in that revision
488
file_id = tree.inventory.path2id(file)
490
raise BzrError("%r is not present in revision %s" % (file, revno))
491
tree.print_file(file_id)
496
def remove(self, files, verbose=False):
497
"""Mark nominated files for removal from the inventory.
499
This does not remove their text. This does not run on
501
TODO: Refuse to remove modified files unless --force is given?
503
TODO: Do something useful with directories.
505
TODO: Should this remove the text or not? Tough call; not
506
removing may be useful and the user can just use use rm, and
507
is the opposite of add. Removing it is consistent with most
508
other tools. Maybe an option.
510
## TODO: Normalize names
511
## TODO: Remove nested loops; better scalability
512
if isinstance(files, basestring):
518
tree = self.working_tree()
521
# do this before any modifications
525
raise BzrError("cannot remove unversioned file %s" % quotefn(f))
526
mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
528
# having remove it, it must be either ignored or unknown
529
if tree.is_ignored(f):
533
show_status(new_status, inv[fid].kind, quotefn(f))
536
self._write_inventory(inv)
541
# FIXME: this doesn't need to be a branch method
542
def set_inventory(self, new_inventory_list):
543
from bzrlib.inventory import Inventory, InventoryEntry
544
inv = Inventory(self.get_root_id())
545
for path, file_id, parent, kind in new_inventory_list:
546
name = os.path.basename(path)
549
inv.add(InventoryEntry(file_id, name, kind, parent))
550
self._write_inventory(inv)
554
"""Return all unknown files.
556
These are files in the working directory that are not versioned or
557
control files or ignored.
559
>>> b = ScratchBranch(files=['foo', 'foo~'])
560
>>> list(b.unknowns())
563
>>> list(b.unknowns())
566
>>> list(b.unknowns())
569
return self.working_tree().unknowns()
572
def append_revision(self, *revision_ids):
573
from bzrlib.atomicfile import AtomicFile
575
for revision_id in revision_ids:
576
mutter("add {%s} to revision-history" % revision_id)
578
rev_history = self.revision_history()
579
rev_history.extend(revision_ids)
581
f = AtomicFile(self.controlfilename('revision-history'))
583
for rev_id in rev_history:
590
def get_revision_xml(self, revision_id):
591
"""Return XML file object for revision object."""
592
if not revision_id or not isinstance(revision_id, basestring):
593
raise InvalidRevisionId(revision_id)
598
return self.revision_store[revision_id]
600
raise bzrlib.errors.NoSuchRevision(self, revision_id)
605
def get_revision(self, revision_id):
606
"""Return the Revision object for a named revision"""
607
xml_file = self.get_revision_xml(revision_id)
610
r = unpack_xml(Revision, xml_file)
611
except SyntaxError, e:
612
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
616
assert r.revision_id == revision_id
386
raise NotImplementedError(self.unlock)
388
def peek_lock_mode(self):
389
"""Return lock mode for the Branch: 'r', 'w' or None"""
390
raise NotImplementedError(self.peek_lock_mode)
392
def get_physical_lock_status(self):
393
raise NotImplementedError(self.get_physical_lock_status)
396
def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
397
"""Return the revision_id for a dotted revno.
399
:param revno: a tuple like (1,) or (1,1,2)
400
:param _cache_reverse: a private parameter enabling storage
401
of the reverse mapping in a top level cache. (This should
402
only be done in selective circumstances as we want to
403
avoid having the mapping cached multiple times.)
404
:return: the revision_id
405
:raises errors.NoSuchRevision: if the revno doesn't exist
407
rev_id = self._do_dotted_revno_to_revision_id(revno)
409
self._partial_revision_id_to_revno_cache[rev_id] = revno
412
def _do_dotted_revno_to_revision_id(self, revno):
413
"""Worker function for dotted_revno_to_revision_id.
415
Subclasses should override this if they wish to
416
provide a more efficient implementation.
419
return self.get_rev_id(revno[0])
420
revision_id_to_revno = self.get_revision_id_to_revno_map()
421
revision_ids = [revision_id for revision_id, this_revno
422
in revision_id_to_revno.iteritems()
423
if revno == this_revno]
424
if len(revision_ids) == 1:
425
return revision_ids[0]
427
revno_str = '.'.join(map(str, revno))
428
raise errors.NoSuchRevision(self, revno_str)
431
def revision_id_to_dotted_revno(self, revision_id):
432
"""Given a revision id, return its dotted revno.
434
:return: a tuple like (1,) or (400,1,3).
436
return self._do_revision_id_to_dotted_revno(revision_id)
438
def _do_revision_id_to_dotted_revno(self, revision_id):
439
"""Worker function for revision_id_to_revno."""
440
# Try the caches if they are loaded
441
result = self._partial_revision_id_to_revno_cache.get(revision_id)
442
if result is not None:
444
if self._revision_id_to_revno_cache:
445
result = self._revision_id_to_revno_cache.get(revision_id)
447
raise errors.NoSuchRevision(self, revision_id)
448
# Try the mainline as it's optimised
450
revno = self.revision_id_to_revno(revision_id)
452
except errors.NoSuchRevision:
453
# We need to load and use the full revno map after all
454
result = self.get_revision_id_to_revno_map().get(revision_id)
456
raise errors.NoSuchRevision(self, revision_id)
460
def get_revision_id_to_revno_map(self):
461
"""Return the revision_id => dotted revno map.
463
This will be regenerated on demand, but will be cached.
465
:return: A dictionary mapping revision_id => dotted revno.
466
This dictionary should not be modified by the caller.
468
if self._revision_id_to_revno_cache is not None:
469
mapping = self._revision_id_to_revno_cache
471
mapping = self._gen_revno_map()
472
self._cache_revision_id_to_revno(mapping)
473
# TODO: jam 20070417 Since this is being cached, should we be returning
475
# I would rather not, and instead just declare that users should not
476
# modify the return value.
479
def _gen_revno_map(self):
480
"""Create a new mapping from revision ids to dotted revnos.
482
Dotted revnos are generated based on the current tip in the revision
484
This is the worker function for get_revision_id_to_revno_map, which
485
just caches the return value.
487
:return: A dictionary mapping revision_id => dotted revno.
489
revision_id_to_revno = dict((rev_id, revno)
490
for rev_id, depth, revno, end_of_merge
491
in self.iter_merge_sorted_revisions())
492
return revision_id_to_revno
495
def iter_merge_sorted_revisions(self, start_revision_id=None,
496
stop_revision_id=None, stop_rule='exclude', direction='reverse'):
497
"""Walk the revisions for a branch in merge sorted order.
499
Merge sorted order is the output from a merge-aware,
500
topological sort, i.e. all parents come before their
501
children going forward; the opposite for reverse.
503
:param start_revision_id: the revision_id to begin walking from.
504
If None, the branch tip is used.
505
:param stop_revision_id: the revision_id to terminate the walk
506
after. If None, the rest of history is included.
507
:param stop_rule: if stop_revision_id is not None, the precise rule
508
to use for termination:
510
* 'exclude' - leave the stop revision out of the result (default)
511
* 'include' - the stop revision is the last item in the result
512
* 'with-merges' - include the stop revision and all of its
513
merged revisions in the result
514
* 'with-merges-without-common-ancestry' - filter out revisions
515
that are in both ancestries
516
:param direction: either 'reverse' or 'forward':
518
* reverse means return the start_revision_id first, i.e.
519
start at the most recent revision and go backwards in history
520
* forward returns tuples in the opposite order to reverse.
521
Note in particular that forward does *not* do any intelligent
522
ordering w.r.t. depth as some clients of this API may like.
523
(If required, that ought to be done at higher layers.)
525
:return: an iterator over (revision_id, depth, revno, end_of_merge)
528
* revision_id: the unique id of the revision
529
* depth: How many levels of merging deep this node has been
531
* revno_sequence: This field provides a sequence of
532
revision numbers for all revisions. The format is:
533
(REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
534
branch that the revno is on. From left to right the REVNO numbers
535
are the sequence numbers within that branch of the revision.
536
* end_of_merge: When True the next node (earlier in history) is
537
part of a different merge.
539
# Note: depth and revno values are in the context of the branch so
540
# we need the full graph to get stable numbers, regardless of the
542
if self._merge_sorted_revisions_cache is None:
543
last_revision = self.last_revision()
544
known_graph = self.repository.get_known_graph_ancestry(
546
self._merge_sorted_revisions_cache = known_graph.merge_sort(
548
filtered = self._filter_merge_sorted_revisions(
549
self._merge_sorted_revisions_cache, start_revision_id,
550
stop_revision_id, stop_rule)
551
# Make sure we don't return revisions that are not part of the
552
# start_revision_id ancestry.
553
filtered = self._filter_start_non_ancestors(filtered)
554
if direction == 'reverse':
556
if direction == 'forward':
557
return reversed(list(filtered))
559
raise ValueError('invalid direction %r' % direction)
561
def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
562
start_revision_id, stop_revision_id, stop_rule):
563
"""Iterate over an inclusive range of sorted revisions."""
564
rev_iter = iter(merge_sorted_revisions)
565
if start_revision_id is not None:
566
for node in rev_iter:
568
if rev_id != start_revision_id:
571
# The decision to include the start or not
572
# depends on the stop_rule if a stop is provided
573
# so pop this node back into the iterator
574
rev_iter = itertools.chain(iter([node]), rev_iter)
576
if stop_revision_id is None:
578
for node in rev_iter:
580
yield (rev_id, node.merge_depth, node.revno,
582
elif stop_rule == 'exclude':
583
for node in rev_iter:
585
if rev_id == stop_revision_id:
587
yield (rev_id, node.merge_depth, node.revno,
589
elif stop_rule == 'include':
590
for node in rev_iter:
592
yield (rev_id, node.merge_depth, node.revno,
594
if rev_id == stop_revision_id:
596
elif stop_rule == 'with-merges-without-common-ancestry':
597
# We want to exclude all revisions that are already part of the
598
# stop_revision_id ancestry.
599
graph = self.repository.get_graph()
600
ancestors = graph.find_unique_ancestors(start_revision_id,
602
for node in rev_iter:
604
if rev_id not in ancestors:
606
yield (rev_id, node.merge_depth, node.revno,
608
elif stop_rule == 'with-merges':
609
stop_rev = self.repository.get_revision(stop_revision_id)
610
if stop_rev.parent_ids:
611
left_parent = stop_rev.parent_ids[0]
613
left_parent = _mod_revision.NULL_REVISION
614
# left_parent is the actual revision we want to stop logging at,
615
# since we want to show the merged revisions after the stop_rev too
616
reached_stop_revision_id = False
617
revision_id_whitelist = []
618
for node in rev_iter:
620
if rev_id == left_parent:
621
# reached the left parent after the stop_revision
623
if (not reached_stop_revision_id or
624
rev_id in revision_id_whitelist):
625
yield (rev_id, node.merge_depth, node.revno,
627
if reached_stop_revision_id or rev_id == stop_revision_id:
628
# only do the merged revs of rev_id from now on
629
rev = self.repository.get_revision(rev_id)
631
reached_stop_revision_id = True
632
revision_id_whitelist.extend(rev.parent_ids)
634
raise ValueError('invalid stop_rule %r' % stop_rule)
636
def _filter_start_non_ancestors(self, rev_iter):
637
# If we started from a dotted revno, we want to consider it as a tip
638
# and don't want to yield revisions that are not part of its
639
# ancestry. Given the order guaranteed by the merge sort, we will see
640
# uninteresting descendants of the first parent of our tip before the
642
first = rev_iter.next()
643
(rev_id, merge_depth, revno, end_of_merge) = first
646
# We start at a mainline revision so by definition, all others
647
# revisions in rev_iter are ancestors
648
for node in rev_iter:
653
pmap = self.repository.get_parent_map([rev_id])
654
parents = pmap.get(rev_id, [])
656
whitelist.update(parents)
658
# If there is no parents, there is nothing of interest left
660
# FIXME: It's hard to test this scenario here as this code is never
661
# called in that case. -- vila 20100322
664
for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
666
if rev_id in whitelist:
667
pmap = self.repository.get_parent_map([rev_id])
668
parents = pmap.get(rev_id, [])
669
whitelist.remove(rev_id)
670
whitelist.update(parents)
672
# We've reached the mainline, there is nothing left to
676
# A revision that is not part of the ancestry of our
679
yield (rev_id, merge_depth, revno, end_of_merge)
681
def leave_lock_in_place(self):
682
"""Tell this branch object not to release the physical lock when this
685
If lock_write doesn't return a token, then this method is not supported.
687
self.control_files.leave_in_place()
689
def dont_leave_lock_in_place(self):
690
"""Tell this branch object to release the physical lock when this
691
object is unlocked, even if it didn't originally acquire it.
693
If lock_write doesn't return a token, then this method is not supported.
695
self.control_files.dont_leave_in_place()
697
def bind(self, other):
698
"""Bind the local branch the other branch.
700
:param other: The branch to bind to
703
raise errors.UpgradeRequired(self.user_url)
705
def get_append_revisions_only(self):
706
"""Whether it is only possible to append revisions to the history.
708
if not self._format.supports_set_append_revisions_only():
710
return self.get_config_stack().get('append_revisions_only')
712
def set_append_revisions_only(self, enabled):
713
if not self._format.supports_set_append_revisions_only():
714
raise errors.UpgradeRequired(self.user_url)
715
self.get_config_stack().set('append_revisions_only', enabled)
717
def set_reference_info(self, file_id, tree_path, branch_location):
718
"""Set the branch location to use for a tree reference."""
719
raise errors.UnsupportedOperation(self.set_reference_info, self)
721
def get_reference_info(self, file_id):
722
"""Get the tree_path and branch_location for a tree reference."""
723
raise errors.UnsupportedOperation(self.get_reference_info, self)
726
def fetch(self, from_branch, last_revision=None, limit=None):
727
"""Copy revisions from from_branch into this branch.
729
:param from_branch: Where to copy from.
730
:param last_revision: What revision to stop at (None for at the end
732
:param limit: Optional rough limit of revisions to fetch
735
return InterBranch.get(from_branch, self).fetch(last_revision, limit=limit)
737
def get_bound_location(self):
738
"""Return the URL of the branch we are bound to.
740
Older format branches cannot bind, please be sure to use a metadir
745
def get_old_bound_location(self):
746
"""Return the URL of the branch we used to be bound to
748
raise errors.UpgradeRequired(self.user_url)
750
def get_commit_builder(self, parents, config_stack=None, timestamp=None,
751
timezone=None, committer=None, revprops=None,
752
revision_id=None, lossy=False):
753
"""Obtain a CommitBuilder for this branch.
755
:param parents: Revision ids of the parents of the new revision.
756
:param config: Optional configuration to use.
757
:param timestamp: Optional timestamp recorded for commit.
758
:param timezone: Optional timezone for timestamp.
759
:param committer: Optional committer to set for commit.
760
:param revprops: Optional dictionary of revision properties.
761
:param revision_id: Optional revision id.
762
:param lossy: Whether to discard data that can not be natively
763
represented, when pushing to a foreign VCS
766
if config_stack is None:
767
config_stack = self.get_config_stack()
769
return self.repository.get_commit_builder(self, parents, config_stack,
770
timestamp, timezone, committer, revprops, revision_id,
773
def get_master_branch(self, possible_transports=None):
774
"""Return the branch we are bound to.
776
:return: Either a Branch, or None
780
@deprecated_method(deprecated_in((2, 5, 0)))
620
781
def get_revision_delta(self, revno):
621
782
"""Return the delta for one revision.
623
784
The delta is relative to its mainline predecessor, or the
624
785
empty tree for revision 1.
626
assert isinstance(revno, int)
627
rh = self.revision_history()
628
if not (1 <= revno <= len(rh)):
629
raise InvalidRevisionNumber(revno)
631
# revno is 1-based; list is 0-based
633
new_tree = self.revision_tree(rh[revno-1])
635
old_tree = EmptyTree()
637
old_tree = self.revision_tree(rh[revno-2])
639
return compare_trees(old_tree, new_tree)
643
def get_revision_sha1(self, revision_id):
644
"""Hash the stored value of a revision, and return it."""
645
# In the future, revision entries will be signed. At that
646
# point, it is probably best *not* to include the signature
647
# in the revision hash. Because that lets you re-sign
648
# the revision, (add signatures/remove signatures) and still
649
# have all hash pointers stay consistent.
650
# But for now, just hash the contents.
651
return bzrlib.osutils.sha_file(self.get_revision_xml(revision_id))
654
def get_inventory(self, inventory_id):
655
"""Get Inventory object by hash.
657
TODO: Perhaps for this and similar methods, take a revision
658
parameter which can be either an integer revno or a
660
from bzrlib.inventory import Inventory
661
from bzrlib.xml import unpack_xml
663
return unpack_xml(Inventory, self.inventory_store[inventory_id])
666
def get_inventory_sha1(self, inventory_id):
667
"""Return the sha1 hash of the inventory entry
669
return sha_file(self.inventory_store[inventory_id])
672
def get_revision_inventory(self, revision_id):
673
"""Return inventory of a past revision."""
674
# bzr 0.0.6 imposes the constraint that the inventory_id
675
# must be the same as its revision, so this is trivial.
676
if revision_id == None:
677
from bzrlib.inventory import Inventory
678
return Inventory(self.get_root_id())
680
return self.get_inventory(revision_id)
683
def revision_history(self):
788
revid = self.get_rev_id(revno)
789
except errors.NoSuchRevision:
790
raise errors.InvalidRevisionNumber(revno)
791
return self.repository.get_revision_delta(revid)
793
def get_stacked_on_url(self):
794
"""Get the URL this branch is stacked against.
796
:raises NotStacked: If the branch is not stacked.
797
:raises UnstackableBranchFormat: If the branch does not support
800
raise NotImplementedError(self.get_stacked_on_url)
802
def print_file(self, file, revision_id):
803
"""Print `file` to stdout."""
804
raise NotImplementedError(self.print_file)
807
def set_last_revision_info(self, revno, revision_id):
808
"""Set the last revision of this branch.
810
The caller is responsible for checking that the revno is correct
811
for this revision id.
813
It may be possible to set the branch last revision to an id not
814
present in the repository. However, branches can also be
815
configured to check constraints on history, in which case this may not
818
raise NotImplementedError(self.set_last_revision_info)
821
def generate_revision_history(self, revision_id, last_rev=None,
823
"""See Branch.generate_revision_history"""
824
graph = self.repository.get_graph()
825
(last_revno, last_revid) = self.last_revision_info()
826
known_revision_ids = [
827
(last_revid, last_revno),
828
(_mod_revision.NULL_REVISION, 0),
830
if last_rev is not None:
831
if not graph.is_ancestor(last_rev, revision_id):
832
# our previous tip is not merged into stop_revision
833
raise errors.DivergedBranches(self, other_branch)
834
revno = graph.find_distance_to_null(revision_id, known_revision_ids)
835
self.set_last_revision_info(revno, revision_id)
838
def set_parent(self, url):
839
"""See Branch.set_parent."""
840
# TODO: Maybe delete old location files?
841
# URLs should never be unicode, even on the local fs,
842
# FIXUP this and get_parent in a future branch format bump:
843
# read and rewrite the file. RBC 20060125
845
if isinstance(url, unicode):
847
url = url.encode('ascii')
848
except UnicodeEncodeError:
849
raise errors.InvalidURL(url,
850
"Urls must be 7-bit ascii, "
851
"use bzrlib.urlutils.escape")
852
url = urlutils.relative_url(self.base, url)
853
self._set_parent_location(url)
856
def set_stacked_on_url(self, url):
857
"""Set the URL this branch is stacked against.
859
:raises UnstackableBranchFormat: If the branch does not support
861
:raises UnstackableRepositoryFormat: If the repository does not support
864
if not self._format.supports_stacking():
865
raise errors.UnstackableBranchFormat(self._format, self.user_url)
866
# XXX: Changing from one fallback repository to another does not check
867
# that all the data you need is present in the new fallback.
868
# Possibly it should.
869
self._check_stackable_repo()
872
old_url = self.get_stacked_on_url()
873
except (errors.NotStacked, errors.UnstackableBranchFormat,
874
errors.UnstackableRepositoryFormat):
878
self._activate_fallback_location(url,
879
possible_transports=[self.bzrdir.root_transport])
880
# write this out after the repository is stacked to avoid setting a
881
# stacked config that doesn't work.
882
self._set_config_location('stacked_on_location', url)
885
"""Change a branch to be unstacked, copying data as needed.
887
Don't call this directly, use set_stacked_on_url(None).
889
pb = ui.ui_factory.nested_progress_bar()
891
pb.update(gettext("Unstacking"))
892
# The basic approach here is to fetch the tip of the branch,
893
# including all available ghosts, from the existing stacked
894
# repository into a new repository object without the fallbacks.
896
# XXX: See <https://launchpad.net/bugs/397286> - this may not be
897
# correct for CHKMap repostiories
898
old_repository = self.repository
899
if len(old_repository._fallback_repositories) != 1:
900
raise AssertionError("can't cope with fallback repositories "
901
"of %r (fallbacks: %r)" % (old_repository,
902
old_repository._fallback_repositories))
903
# Open the new repository object.
904
# Repositories don't offer an interface to remove fallback
905
# repositories today; take the conceptually simpler option and just
906
# reopen it. We reopen it starting from the URL so that we
907
# get a separate connection for RemoteRepositories and can
908
# stream from one of them to the other. This does mean doing
909
# separate SSH connection setup, but unstacking is not a
910
# common operation so it's tolerable.
911
new_bzrdir = controldir.ControlDir.open(
912
self.bzrdir.root_transport.base)
913
new_repository = new_bzrdir.find_repository()
914
if new_repository._fallback_repositories:
915
raise AssertionError("didn't expect %r to have "
916
"fallback_repositories"
917
% (self.repository,))
918
# Replace self.repository with the new repository.
919
# Do our best to transfer the lock state (i.e. lock-tokens and
920
# lock count) of self.repository to the new repository.
921
lock_token = old_repository.lock_write().repository_token
922
self.repository = new_repository
923
if isinstance(self, remote.RemoteBranch):
924
# Remote branches can have a second reference to the old
925
# repository that need to be replaced.
926
if self._real_branch is not None:
927
self._real_branch.repository = new_repository
928
self.repository.lock_write(token=lock_token)
929
if lock_token is not None:
930
old_repository.leave_lock_in_place()
931
old_repository.unlock()
932
if lock_token is not None:
933
# XXX: self.repository.leave_lock_in_place() before this
934
# function will not be preserved. Fortunately that doesn't
935
# affect the current default format (2a), and would be a
936
# corner-case anyway.
937
# - Andrew Bennetts, 2010/06/30
938
self.repository.dont_leave_lock_in_place()
942
old_repository.unlock()
943
except errors.LockNotHeld:
946
if old_lock_count == 0:
947
raise AssertionError(
948
'old_repository should have been locked at least once.')
949
for i in range(old_lock_count-1):
950
self.repository.lock_write()
951
# Fetch from the old repository into the new.
952
old_repository.lock_read()
954
# XXX: If you unstack a branch while it has a working tree
955
# with a pending merge, the pending-merged revisions will no
956
# longer be present. You can (probably) revert and remerge.
958
tags_to_fetch = set(self.tags.get_reverse_tag_dict())
959
except errors.TagsNotSupported:
960
tags_to_fetch = set()
961
fetch_spec = vf_search.NotInOtherForRevs(self.repository,
962
old_repository, required_ids=[self.last_revision()],
963
if_present_ids=tags_to_fetch, find_ghosts=True).execute()
964
self.repository.fetch(old_repository, fetch_spec=fetch_spec)
966
old_repository.unlock()
970
def _set_tags_bytes(self, bytes):
971
"""Mirror method for _get_tags_bytes.
973
:seealso: Branch._get_tags_bytes.
975
op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
976
op.add_cleanup(self.lock_write().unlock)
977
return op.run_simple(bytes)
979
def _set_tags_bytes_locked(self, bytes):
980
self._tags_bytes = bytes
981
return self._transport.put_bytes('tags', bytes)
983
def _cache_revision_history(self, rev_history):
984
"""Set the cached revision history to rev_history.
986
The revision_history method will use this cache to avoid regenerating
987
the revision history.
989
This API is semi-public; it only for use by subclasses, all other code
990
should consider it to be private.
992
self._revision_history_cache = rev_history
994
def _cache_revision_id_to_revno(self, revision_id_to_revno):
995
"""Set the cached revision_id => revno map to revision_id_to_revno.
997
This API is semi-public; it only for use by subclasses, all other code
998
should consider it to be private.
1000
self._revision_id_to_revno_cache = revision_id_to_revno
1002
def _clear_cached_state(self):
1003
"""Clear any cached data on this branch, e.g. cached revision history.
1005
This means the next call to revision_history will need to call
1006
_gen_revision_history.
1008
This API is semi-public; it is only for use by subclasses, all other
1009
code should consider it to be private.
1011
self._revision_history_cache = None
1012
self._revision_id_to_revno_cache = None
1013
self._last_revision_info_cache = None
1014
self._master_branch_cache = None
1015
self._merge_sorted_revisions_cache = None
1016
self._partial_revision_history_cache = []
1017
self._partial_revision_id_to_revno_cache = {}
1018
self._tags_bytes = None
1020
def _gen_revision_history(self):
684
1021
"""Return sequence of revision hashes on to this branch.
686
>>> ScratchBranch().revision_history()
691
return [l.rstrip('\r\n') for l in
692
self.controlfile('revision-history', 'r').readlines()]
697
def common_ancestor(self, other, self_revno=None, other_revno=None):
700
>>> sb = ScratchBranch(files=['foo', 'foo~'])
701
>>> sb.common_ancestor(sb) == (None, None)
703
>>> commit.commit(sb, "Committing first revision", verbose=False)
704
>>> sb.common_ancestor(sb)[0]
706
>>> clone = sb.clone()
707
>>> commit.commit(sb, "Committing second revision", verbose=False)
708
>>> sb.common_ancestor(sb)[0]
710
>>> sb.common_ancestor(clone)[0]
712
>>> commit.commit(clone, "Committing divergent second revision",
714
>>> sb.common_ancestor(clone)[0]
716
>>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
718
>>> sb.common_ancestor(sb) != clone.common_ancestor(clone)
720
>>> clone2 = sb.clone()
721
>>> sb.common_ancestor(clone2)[0]
723
>>> sb.common_ancestor(clone2, self_revno=1)[0]
725
>>> sb.common_ancestor(clone2, other_revno=1)[0]
728
my_history = self.revision_history()
729
other_history = other.revision_history()
730
if self_revno is None:
731
self_revno = len(my_history)
732
if other_revno is None:
733
other_revno = len(other_history)
734
indices = range(min((self_revno, other_revno)))
737
if my_history[r] == other_history[r]:
738
return r+1, my_history[r]
1023
Unlike revision_history, this method always regenerates or rereads the
1024
revision history, i.e. it does not cache the result, so repeated calls
1027
Concrete subclasses should override this instead of revision_history so
1028
that subclasses do not need to deal with caching logic.
1030
This API is semi-public; it only for use by subclasses, all other code
1031
should consider it to be private.
1033
raise NotImplementedError(self._gen_revision_history)
1035
def _revision_history(self):
1036
if 'evil' in debug.debug_flags:
1037
mutter_callsite(3, "revision_history scales with history.")
1038
if self._revision_history_cache is not None:
1039
history = self._revision_history_cache
1041
history = self._gen_revision_history()
1042
self._cache_revision_history(history)
1043
return list(history)
742
1045
def revno(self):
743
1046
"""Return current revision number for this branch.
745
1048
That is equivalent to the number of revisions committed to
748
return len(self.revision_history())
751
def last_patch(self):
752
"""Return last patch hash, or None if no history.
754
ph = self.revision_history()
761
def missing_revisions(self, other, stop_revision=None):
763
If self and other have not diverged, return a list of the revisions
764
present in other, but missing from self.
766
>>> from bzrlib.commit import commit
767
>>> bzrlib.trace.silent = True
768
>>> br1 = ScratchBranch()
769
>>> br2 = ScratchBranch()
770
>>> br1.missing_revisions(br2)
772
>>> commit(br2, "lala!", rev_id="REVISION-ID-1")
773
>>> br1.missing_revisions(br2)
775
>>> br2.missing_revisions(br1)
777
>>> commit(br1, "lala!", rev_id="REVISION-ID-1")
778
>>> br1.missing_revisions(br2)
780
>>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
781
>>> br1.missing_revisions(br2)
783
>>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
784
>>> br1.missing_revisions(br2)
785
Traceback (most recent call last):
786
DivergedBranches: These branches have diverged.
788
self_history = self.revision_history()
789
self_len = len(self_history)
790
other_history = other.revision_history()
791
other_len = len(other_history)
792
common_index = min(self_len, other_len) -1
793
if common_index >= 0 and \
794
self_history[common_index] != other_history[common_index]:
795
raise DivergedBranches(self, other)
797
if stop_revision is None:
798
stop_revision = other_len
799
elif stop_revision > other_len:
800
raise NoSuchRevision(self, stop_revision)
802
return other_history[self_len:stop_revision]
805
def update_revisions(self, other, stop_revision=None):
806
"""Pull in all new revisions from other branch.
808
>>> from bzrlib.commit import commit
809
>>> bzrlib.trace.silent = True
810
>>> br1 = ScratchBranch(files=['foo', 'bar'])
813
>>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
814
>>> br2 = ScratchBranch()
815
>>> br2.update_revisions(br1)
819
>>> br2.revision_history()
821
>>> br2.update_revisions(br1)
825
>>> br1.text_store.total_size() == br2.text_store.total_size()
828
from bzrlib.progress import ProgressBar
832
pb.update('comparing histories')
833
revision_ids = self.missing_revisions(other, stop_revision)
835
if hasattr(other.revision_store, "prefetch"):
836
other.revision_store.prefetch(revision_ids)
837
if hasattr(other.inventory_store, "prefetch"):
838
inventory_ids = [other.get_revision(r).inventory_id
839
for r in revision_ids]
840
other.inventory_store.prefetch(inventory_ids)
845
for rev_id in revision_ids:
847
pb.update('fetching revision', i, len(revision_ids))
848
rev = other.get_revision(rev_id)
849
revisions.append(rev)
850
inv = other.get_inventory(str(rev.inventory_id))
851
for key, entry in inv.iter_entries():
852
if entry.text_id is None:
854
if entry.text_id not in self.text_store:
855
needed_texts.add(entry.text_id)
859
count = self.text_store.copy_multi(other.text_store, needed_texts)
860
print "Added %d texts." % count
861
inventory_ids = [ f.inventory_id for f in revisions ]
862
count = self.inventory_store.copy_multi(other.inventory_store,
864
print "Added %d inventories." % count
865
revision_ids = [ f.revision_id for f in revisions]
866
count = self.revision_store.copy_multi(other.revision_store,
868
for revision_id in revision_ids:
869
self.append_revision(revision_id)
870
print "Added %d revisions." % count
873
def commit(self, *args, **kw):
874
from bzrlib.commit import commit
875
commit(self, *args, **kw)
878
def lookup_revision(self, revision):
879
"""Return the revision identifier for a given revision information."""
880
revno, info = self.get_revision_info(revision)
883
def get_revision_info(self, revision):
884
"""Return (revno, revision id) for revision identifier.
886
revision can be an integer, in which case it is assumed to be revno (though
887
this will translate negative values into positive ones)
888
revision can also be a string, in which case it is parsed for something like
889
'date:' or 'revid:' etc.
894
try:# Convert to int if possible
895
revision = int(revision)
1051
return self.last_revision_info()[0]
1054
"""Older format branches cannot bind or unbind."""
1055
raise errors.UpgradeRequired(self.user_url)
1057
def last_revision(self):
1058
"""Return last revision id, or NULL_REVISION."""
1059
return self.last_revision_info()[1]
1062
def last_revision_info(self):
1063
"""Return information about the last revision.
1065
:return: A tuple (revno, revision_id).
1067
if self._last_revision_info_cache is None:
1068
self._last_revision_info_cache = self._read_last_revision_info()
1069
return self._last_revision_info_cache
1071
def _read_last_revision_info(self):
1072
raise NotImplementedError(self._read_last_revision_info)
1074
def import_last_revision_info_and_tags(self, source, revno, revid,
1076
"""Set the last revision info, importing from another repo if necessary.
1078
This is used by the bound branch code to upload a revision to
1079
the master branch first before updating the tip of the local branch.
1080
Revisions referenced by source's tags are also transferred.
1082
:param source: Source branch to optionally fetch from
1083
:param revno: Revision number of the new tip
1084
:param revid: Revision id of the new tip
1085
:param lossy: Whether to discard metadata that can not be
1086
natively represented
1087
:return: Tuple with the new revision number and revision id
1088
(should only be different from the arguments when lossy=True)
1090
if not self.repository.has_same_location(source.repository):
1091
self.fetch(source, revid)
1092
self.set_last_revision_info(revno, revid)
1093
return (revno, revid)
1095
def revision_id_to_revno(self, revision_id):
1096
"""Given a revision id, return its revno"""
1097
if _mod_revision.is_null(revision_id):
1099
history = self._revision_history()
1101
return history.index(revision_id) + 1
896
1102
except ValueError:
1103
raise errors.NoSuchRevision(self, revision_id)
1106
def get_rev_id(self, revno, history=None):
1107
"""Find the revision id of the specified revno."""
1109
return _mod_revision.NULL_REVISION
1110
last_revno, last_revid = self.last_revision_info()
1111
if revno == last_revno:
1113
if revno <= 0 or revno > last_revno:
1114
raise errors.NoSuchRevision(self, revno)
1115
distance_from_last = last_revno - revno
1116
if len(self._partial_revision_history_cache) <= distance_from_last:
1117
self._extend_partial_history(distance_from_last)
1118
return self._partial_revision_history_cache[distance_from_last]
1120
def pull(self, source, overwrite=False, stop_revision=None,
1121
possible_transports=None, *args, **kwargs):
1122
"""Mirror source into this branch.
1124
This branch is considered to be 'local', having low latency.
1126
:returns: PullResult instance
1128
return InterBranch.get(source, self).pull(overwrite=overwrite,
1129
stop_revision=stop_revision,
1130
possible_transports=possible_transports, *args, **kwargs)
1132
def push(self, target, overwrite=False, stop_revision=None, lossy=False,
1134
"""Mirror this branch into target.
1136
This branch is considered to be 'local', having low latency.
1138
return InterBranch.get(self, target).push(overwrite, stop_revision,
1139
lossy, *args, **kwargs)
1141
def basis_tree(self):
1142
"""Return `Tree` object for last revision."""
1143
return self.repository.revision_tree(self.last_revision())
1145
def get_parent(self):
1146
"""Return the parent location of the branch.
1148
This is the default location for pull/missing. The usual
1149
pattern is that the user can override it by specifying a
1152
parent = self._get_parent_location()
1155
# This is an old-format absolute path to a local branch
1156
# turn it into a url
1157
if parent.startswith('/'):
1158
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1160
return urlutils.join(self.base[:-1], parent)
1161
except errors.InvalidURLJoin, e:
1162
raise errors.InaccessibleParent(parent, self.user_url)
1164
def _get_parent_location(self):
1165
raise NotImplementedError(self._get_parent_location)
1167
def _set_config_location(self, name, url, config=None,
1168
make_relative=False):
1170
config = self.get_config_stack()
1174
url = urlutils.relative_url(self.base, url)
1175
config.set(name, url)
1177
def _get_config_location(self, name, config=None):
1179
config = self.get_config_stack()
1180
location = config.get(name)
1185
def get_child_submit_format(self):
1186
"""Return the preferred format of submissions to this branch."""
1187
return self.get_config_stack().get('child_submit_format')
1189
def get_submit_branch(self):
1190
"""Return the submit location of the branch.
1192
This is the default location for bundle. The usual
1193
pattern is that the user can override it by specifying a
1196
return self.get_config_stack().get('submit_branch')
1198
def set_submit_branch(self, location):
1199
"""Return the submit location of the branch.
1201
This is the default location for bundle. The usual
1202
pattern is that the user can override it by specifying a
1205
self.get_config_stack().set('submit_branch', location)
1207
def get_public_branch(self):
1208
"""Return the public location of the branch.
1210
This is used by merge directives.
1212
return self._get_config_location('public_branch')
1214
def set_public_branch(self, location):
1215
"""Return the submit location of the branch.
1217
This is the default location for bundle. The usual
1218
pattern is that the user can override it by specifying a
1221
self._set_config_location('public_branch', location)
1223
def get_push_location(self):
1224
"""Return None or the location to push this branch to."""
1225
return self.get_config_stack().get('push_location')
1227
def set_push_location(self, location):
1228
"""Set a new push location for this branch."""
1229
raise NotImplementedError(self.set_push_location)
1231
def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
1232
"""Run the post_change_branch_tip hooks."""
1233
hooks = Branch.hooks['post_change_branch_tip']
1236
new_revno, new_revid = self.last_revision_info()
1237
params = ChangeBranchTipParams(
1238
self, old_revno, new_revno, old_revid, new_revid)
1242
def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
1243
"""Run the pre_change_branch_tip hooks."""
1244
hooks = Branch.hooks['pre_change_branch_tip']
1247
old_revno, old_revid = self.last_revision_info()
1248
params = ChangeBranchTipParams(
1249
self, old_revno, new_revno, old_revid, new_revid)
1255
"""Synchronise this branch with the master branch if any.
1257
:return: None or the last_revision pivoted out during the update.
1261
def check_revno(self, revno):
1263
Check whether a revno corresponds to any revision.
1264
Zero (the NULL revision) is considered valid.
1267
self.check_real_revno(revno)
1269
def check_real_revno(self, revno):
1271
Check whether a revno corresponds to a real revision.
1272
Zero (the NULL revision) is considered invalid
1274
if revno < 1 or revno > self.revno():
1275
raise errors.InvalidRevisionNumber(revno)
1278
def clone(self, to_bzrdir, revision_id=None, repository_policy=None):
1279
"""Clone this branch into to_bzrdir preserving all semantic values.
1281
Most API users will want 'create_clone_on_transport', which creates a
1282
new bzrdir and branch on the fly.
1284
revision_id: if not None, the revision history in the new branch will
1285
be truncated to end with revision_id.
1287
result = to_bzrdir.create_branch()
1290
if repository_policy is not None:
1291
repository_policy.configure_branch(result)
1292
self.copy_content_into(result, revision_id=revision_id)
1298
def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
1300
"""Create a new line of development from the branch, into to_bzrdir.
1302
to_bzrdir controls the branch format.
1304
revision_id: if not None, the revision history in the new branch will
1305
be truncated to end with revision_id.
1307
if (repository_policy is not None and
1308
repository_policy.requires_stacking()):
1309
to_bzrdir._format.require_stacking(_skip_repo=True)
1310
result = to_bzrdir.create_branch(repository=repository)
1313
if repository_policy is not None:
1314
repository_policy.configure_branch(result)
1315
self.copy_content_into(result, revision_id=revision_id)
1316
master_url = self.get_bound_location()
1317
if master_url is None:
1318
result.set_parent(self.bzrdir.root_transport.base)
1320
result.set_parent(master_url)
1325
def _synchronize_history(self, destination, revision_id):
1326
"""Synchronize last revision and revision history between branches.
1328
This version is most efficient when the destination is also a
1329
BzrBranch6, but works for BzrBranch5, as long as the destination's
1330
repository contains all the lefthand ancestors of the intended
1331
last_revision. If not, set_last_revision_info will fail.
1333
:param destination: The branch to copy the history into
1334
:param revision_id: The revision-id to truncate history at. May
1335
be None to copy complete history.
1337
source_revno, source_revision_id = self.last_revision_info()
1338
if revision_id is None:
1339
revno, revision_id = source_revno, source_revision_id
1341
graph = self.repository.get_graph()
1343
revno = graph.find_distance_to_null(revision_id,
1344
[(source_revision_id, source_revno)])
1345
except errors.GhostRevisionsHaveNoRevno:
1346
# Default to 1, if we can't find anything else
1348
destination.set_last_revision_info(revno, revision_id)
1350
def copy_content_into(self, destination, revision_id=None):
1351
"""Copy the content of self into destination.
1353
revision_id: if not None, the revision history in the new branch will
1354
be truncated to end with revision_id.
1356
return InterBranch.get(self, destination).copy_content_into(
1357
revision_id=revision_id)
1359
def update_references(self, target):
1360
if not getattr(self._format, 'supports_reference_locations', False):
1362
reference_dict = self._get_all_reference_info()
1363
if len(reference_dict) == 0:
1365
old_base = self.base
1366
new_base = target.base
1367
target_reference_dict = target._get_all_reference_info()
1368
for file_id, (tree_path, branch_location) in (
1369
reference_dict.items()):
1370
branch_location = urlutils.rebase_url(branch_location,
1372
target_reference_dict.setdefault(
1373
file_id, (tree_path, branch_location))
1374
target._set_all_reference_info(target_reference_dict)
1377
def check(self, refs):
1378
"""Check consistency of the branch.
1380
In particular this checks that revisions given in the revision-history
1381
do actually match up in the revision graph, and that they're all
1382
present in the repository.
1384
Callers will typically also want to check the repository.
1386
:param refs: Calculated refs for this branch as specified by
1387
branch._get_check_refs()
1388
:return: A BranchCheckResult.
1390
result = BranchCheckResult(self)
1391
last_revno, last_revision_id = self.last_revision_info()
1392
actual_revno = refs[('lefthand-distance', last_revision_id)]
1393
if actual_revno != last_revno:
1394
result.errors.append(errors.BzrCheckError(
1395
'revno does not match len(mainline) %s != %s' % (
1396
last_revno, actual_revno)))
1397
# TODO: We should probably also check that self.revision_history
1398
# matches the repository for older branch formats.
1399
# If looking for the code that cross-checks repository parents against
1400
# the Graph.iter_lefthand_ancestry output, that is now a repository
1404
def _get_checkout_format(self, lightweight=False):
1405
"""Return the most suitable metadir for a checkout of this branch.
1406
Weaves are used if this branch's repository uses weaves.
1408
format = self.repository.bzrdir.checkout_metadir()
1409
format.set_branch_format(self._format)
1412
def create_clone_on_transport(self, to_transport, revision_id=None,
1413
stacked_on=None, create_prefix=False, use_existing_dir=False,
1415
"""Create a clone of this branch and its bzrdir.
1417
:param to_transport: The transport to clone onto.
1418
:param revision_id: The revision id to use as tip in the new branch.
1419
If None the tip is obtained from this branch.
1420
:param stacked_on: An optional URL to stack the clone on.
1421
:param create_prefix: Create any missing directories leading up to
1423
:param use_existing_dir: Use an existing directory if one exists.
1425
# XXX: Fix the bzrdir API to allow getting the branch back from the
1426
# clone call. Or something. 20090224 RBC/spiv.
1427
# XXX: Should this perhaps clone colocated branches as well,
1428
# rather than just the default branch? 20100319 JRV
1429
if revision_id is None:
1430
revision_id = self.last_revision()
1431
dir_to = self.bzrdir.clone_on_transport(to_transport,
1432
revision_id=revision_id, stacked_on=stacked_on,
1433
create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1435
return dir_to.open_branch()
1437
def create_checkout(self, to_location, revision_id=None,
1438
lightweight=False, accelerator_tree=None,
1440
"""Create a checkout of a branch.
1442
:param to_location: The url to produce the checkout at
1443
:param revision_id: The revision to check out
1444
:param lightweight: If True, produce a lightweight checkout, otherwise,
1445
produce a bound branch (heavyweight checkout)
1446
:param accelerator_tree: A tree which can be used for retrieving file
1447
contents more quickly than the revision tree, i.e. a workingtree.
1448
The revision tree will be used for cases where accelerator_tree's
1449
content is different.
1450
:param hardlink: If true, hard-link files from accelerator_tree,
1452
:return: The tree of the created checkout
1454
t = transport.get_transport(to_location)
1456
format = self._get_checkout_format(lightweight=lightweight)
1458
checkout = format.initialize_on_transport(t)
1459
except errors.AlreadyControlDirError:
1460
# It's fine if the control directory already exists,
1461
# as long as there is no existing branch and working tree.
1462
checkout = controldir.ControlDir.open_from_transport(t)
1464
checkout.open_branch()
1465
except errors.NotBranchError:
1468
raise errors.AlreadyControlDirError(t.base)
1469
if checkout.control_transport.base == self.bzrdir.control_transport.base:
1470
# When checking out to the same control directory,
1471
# always create a lightweight checkout
1475
from_branch = checkout.set_branch_reference(target_branch=self)
1477
policy = checkout.determine_repository_policy()
1478
repo = policy.acquire_repository()[0]
1479
checkout_branch = checkout.create_branch()
1480
checkout_branch.bind(self)
1481
# pull up to the specified revision_id to set the initial
1482
# branch tip correctly, and seed it with history.
1483
checkout_branch.pull(self, stop_revision=revision_id)
1485
tree = checkout.create_workingtree(revision_id,
1486
from_branch=from_branch,
1487
accelerator_tree=accelerator_tree,
1489
basis_tree = tree.basis_tree()
1490
basis_tree.lock_read()
1492
for path, file_id in basis_tree.iter_references():
1493
reference_parent = self.reference_parent(file_id, path)
1494
reference_parent.create_checkout(tree.abspath(path),
1495
basis_tree.get_reference_revision(file_id, path),
1502
def reconcile(self, thorough=True):
1503
"""Make sure the data stored in this branch is consistent."""
1504
from bzrlib.reconcile import BranchReconciler
1505
reconciler = BranchReconciler(self, thorough=thorough)
1506
reconciler.reconcile()
1509
def reference_parent(self, file_id, path, possible_transports=None):
1510
"""Return the parent branch for a tree-reference file_id
1512
:param file_id: The file_id of the tree reference
1513
:param path: The path of the file_id in the tree
1514
:return: A branch associated with the file_id
1516
# FIXME should provide multiple branches, based on config
1517
return Branch.open(self.bzrdir.root_transport.clone(path).base,
1518
possible_transports=possible_transports)
1520
def supports_tags(self):
1521
return self._format.supports_tags()
1523
def automatic_tag_name(self, revision_id):
1524
"""Try to automatically find the tag name for a revision.
1526
:param revision_id: Revision id of the revision.
1527
:return: A tag name or None if no tag name could be determined.
1529
for hook in Branch.hooks['automatic_tag_name']:
1530
ret = hook(self, revision_id)
1535
def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1537
"""Ensure that revision_b is a descendant of revision_a.
1539
This is a helper function for update_revisions.
1541
:raises: DivergedBranches if revision_b has diverged from revision_a.
1542
:returns: True if revision_b is a descendant of revision_a.
1544
relation = self._revision_relations(revision_a, revision_b, graph)
1545
if relation == 'b_descends_from_a':
1547
elif relation == 'diverged':
1548
raise errors.DivergedBranches(self, other_branch)
1549
elif relation == 'a_descends_from_b':
1552
raise AssertionError("invalid relation: %r" % (relation,))
1554
def _revision_relations(self, revision_a, revision_b, graph):
1555
"""Determine the relationship between two revisions.
1557
:returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
1559
heads = graph.heads([revision_a, revision_b])
1560
if heads == set([revision_b]):
1561
return 'b_descends_from_a'
1562
elif heads == set([revision_a, revision_b]):
1563
# These branches have diverged
1565
elif heads == set([revision_a]):
1566
return 'a_descends_from_b'
1568
raise AssertionError("invalid heads: %r" % (heads,))
1570
def heads_to_fetch(self):
1571
"""Return the heads that must and that should be fetched to copy this
1572
branch into another repo.
1574
:returns: a 2-tuple of (must_fetch, if_present_fetch). must_fetch is a
1575
set of heads that must be fetched. if_present_fetch is a set of
1576
heads that must be fetched if present, but no error is necessary if
1577
they are not present.
1579
# For bzr native formats must_fetch is just the tip, and
1580
# if_present_fetch are the tags.
1581
must_fetch = set([self.last_revision()])
1582
if_present_fetch = set()
1583
if self.get_config_stack().get('branch.fetch_tags'):
1585
if_present_fetch = set(self.tags.get_reverse_tag_dict())
1586
except errors.TagsNotSupported:
1588
must_fetch.discard(_mod_revision.NULL_REVISION)
1589
if_present_fetch.discard(_mod_revision.NULL_REVISION)
1590
return must_fetch, if_present_fetch
1593
class BranchFormat(controldir.ControlComponentFormat):
1594
"""An encapsulation of the initialization and open routines for a format.
1596
Formats provide three things:
1597
* An initialization routine,
1598
* a format description
1601
Formats are placed in an dict by their format string for reference
1602
during branch opening. It's not required that these be instances, they
1603
can be classes themselves with class methods - it simply depends on
1604
whether state is needed for a given format or not.
1606
Once a format is deprecated, just deprecate the initialize and open
1607
methods on the format class. Do not deprecate the object, as the
1608
object will be created every time regardless.
1611
def __eq__(self, other):
1612
return self.__class__ is other.__class__
1614
def __ne__(self, other):
1615
return not (self == other)
1617
def get_reference(self, controldir, name=None):
1618
"""Get the target reference of the branch in controldir.
1620
format probing must have been completed before calling
1621
this method - it is assumed that the format of the branch
1622
in controldir is correct.
1624
:param controldir: The controldir to get the branch data from.
1625
:param name: Name of the colocated branch to fetch
1626
:return: None if the branch is not a reference branch.
1631
def set_reference(self, controldir, name, to_branch):
1632
"""Set the target reference of the branch in controldir.
1634
format probing must have been completed before calling
1635
this method - it is assumed that the format of the branch
1636
in controldir is correct.
1638
:param controldir: The controldir to set the branch reference for.
1639
:param name: Name of colocated branch to set, None for default
1640
:param to_branch: branch that the checkout is to reference
1642
raise NotImplementedError(self.set_reference)
1644
def get_format_description(self):
1645
"""Return the short format description for this format."""
1646
raise NotImplementedError(self.get_format_description)
1648
def _run_post_branch_init_hooks(self, controldir, name, branch):
1649
hooks = Branch.hooks['post_branch_init']
1652
params = BranchInitHookParams(self, controldir, name, branch)
1656
def initialize(self, controldir, name=None, repository=None,
1657
append_revisions_only=None):
1658
"""Create a branch of this format in controldir.
1660
:param name: Name of the colocated branch to create.
1662
raise NotImplementedError(self.initialize)
1664
def is_supported(self):
1665
"""Is this format supported?
1667
Supported formats can be initialized and opened.
1668
Unsupported formats may not support initialization or committing or
1669
some other features depending on the reason for not being supported.
1673
def make_tags(self, branch):
1674
"""Create a tags object for branch.
1676
This method is on BranchFormat, because BranchFormats are reflected
1677
over the wire via network_name(), whereas full Branch instances require
1678
multiple VFS method calls to operate at all.
1680
The default implementation returns a disabled-tags instance.
1682
Note that it is normal for branch to be a RemoteBranch when using tags
1685
return _mod_tag.DisabledTags(branch)
1687
def network_name(self):
1688
"""A simple byte string uniquely identifying this format for RPC calls.
1690
MetaDir branch formats use their disk format string to identify the
1691
repository over the wire. All in one formats such as bzr < 0.8, and
1692
foreign formats like svn/git and hg should use some marker which is
1693
unique and immutable.
1695
raise NotImplementedError(self.network_name)
1697
def open(self, controldir, name=None, _found=False, ignore_fallbacks=False,
1698
found_repository=None, possible_transports=None):
1699
"""Return the branch object for controldir.
1701
:param controldir: A ControlDir that contains a branch.
1702
:param name: Name of colocated branch to open
1703
:param _found: a private parameter, do not use it. It is used to
1704
indicate if format probing has already be done.
1705
:param ignore_fallbacks: when set, no fallback branches will be opened
1706
(if there are any). Default is to open fallbacks.
1708
raise NotImplementedError(self.open)
1710
def supports_set_append_revisions_only(self):
1711
"""True if this format supports set_append_revisions_only."""
1714
def supports_stacking(self):
1715
"""True if this format records a stacked-on branch."""
1718
def supports_leaving_lock(self):
1719
"""True if this format supports leaving locks in place."""
1720
return False # by default
1723
return self.get_format_description().rstrip()
1725
def supports_tags(self):
1726
"""True if this format supports tags stored in the branch"""
1727
return False # by default
1729
def tags_are_versioned(self):
1730
"""Whether the tag container for this branch versions tags."""
1733
def supports_tags_referencing_ghosts(self):
1734
"""True if tags can reference ghost revisions."""
1738
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1739
"""A factory for a BranchFormat object, permitting simple lazy registration.
1741
While none of the built in BranchFormats are lazy registered yet,
1742
bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1743
use it, and the bzr-loom plugin uses it as well (see
1744
bzrlib.plugins.loom.formats).
1747
def __init__(self, format_string, module_name, member_name):
1748
"""Create a MetaDirBranchFormatFactory.
1750
:param format_string: The format string the format has.
1751
:param module_name: Module to load the format class from.
1752
:param member_name: Attribute name within the module for the format class.
1754
registry._LazyObjectGetter.__init__(self, module_name, member_name)
1755
self._format_string = format_string
1757
def get_format_string(self):
1758
"""See BranchFormat.get_format_string."""
1759
return self._format_string
1762
"""Used for network_format_registry support."""
1763
return self.get_obj()()
1766
class BranchHooks(Hooks):
1767
"""A dictionary mapping hook name to a list of callables for branch hooks.
1769
e.g. ['post_push'] Is the list of items to be called when the
1770
push function is invoked.
1774
"""Create the default hooks.
1776
These are all empty initially, because by default nothing should get
1779
Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
1780
self.add_hook('open',
1781
"Called with the Branch object that has been opened after a "
1782
"branch is opened.", (1, 8))
1783
self.add_hook('post_push',
1784
"Called after a push operation completes. post_push is called "
1785
"with a bzrlib.branch.BranchPushResult object and only runs in the "
1786
"bzr client.", (0, 15))
1787
self.add_hook('post_pull',
1788
"Called after a pull operation completes. post_pull is called "
1789
"with a bzrlib.branch.PullResult object and only runs in the "
1790
"bzr client.", (0, 15))
1791
self.add_hook('pre_commit',
1792
"Called after a commit is calculated but before it is "
1793
"completed. pre_commit is called with (local, master, old_revno, "
1794
"old_revid, future_revno, future_revid, tree_delta, future_tree"
1795
"). old_revid is NULL_REVISION for the first commit to a branch, "
1796
"tree_delta is a TreeDelta object describing changes from the "
1797
"basis revision. hooks MUST NOT modify this delta. "
1798
" future_tree is an in-memory tree obtained from "
1799
"CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1801
self.add_hook('post_commit',
1802
"Called in the bzr client after a commit has completed. "
1803
"post_commit is called with (local, master, old_revno, old_revid, "
1804
"new_revno, new_revid). old_revid is NULL_REVISION for the first "
1805
"commit to a branch.", (0, 15))
1806
self.add_hook('post_uncommit',
1807
"Called in the bzr client after an uncommit completes. "
1808
"post_uncommit is called with (local, master, old_revno, "
1809
"old_revid, new_revno, new_revid) where local is the local branch "
1810
"or None, master is the target branch, and an empty branch "
1811
"receives new_revno of 0, new_revid of None.", (0, 15))
1812
self.add_hook('pre_change_branch_tip',
1813
"Called in bzr client and server before a change to the tip of a "
1814
"branch is made. pre_change_branch_tip is called with a "
1815
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1816
"commit, uncommit will all trigger this hook.", (1, 6))
1817
self.add_hook('post_change_branch_tip',
1818
"Called in bzr client and server after a change to the tip of a "
1819
"branch is made. post_change_branch_tip is called with a "
1820
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1821
"commit, uncommit will all trigger this hook.", (1, 4))
1822
self.add_hook('transform_fallback_location',
1823
"Called when a stacked branch is activating its fallback "
1824
"locations. transform_fallback_location is called with (branch, "
1825
"url), and should return a new url. Returning the same url "
1826
"allows it to be used as-is, returning a different one can be "
1827
"used to cause the branch to stack on a closer copy of that "
1828
"fallback_location. Note that the branch cannot have history "
1829
"accessing methods called on it during this hook because the "
1830
"fallback locations have not been activated. When there are "
1831
"multiple hooks installed for transform_fallback_location, "
1832
"all are called with the url returned from the previous hook."
1833
"The order is however undefined.", (1, 9))
1834
self.add_hook('automatic_tag_name',
1835
"Called to determine an automatic tag name for a revision. "
1836
"automatic_tag_name is called with (branch, revision_id) and "
1837
"should return a tag name or None if no tag name could be "
1838
"determined. The first non-None tag name returned will be used.",
1840
self.add_hook('post_branch_init',
1841
"Called after new branch initialization completes. "
1842
"post_branch_init is called with a "
1843
"bzrlib.branch.BranchInitHookParams. "
1844
"Note that init, branch and checkout (both heavyweight and "
1845
"lightweight) will all trigger this hook.", (2, 2))
1846
self.add_hook('post_switch',
1847
"Called after a checkout switches branch. "
1848
"post_switch is called with a "
1849
"bzrlib.branch.SwitchHookParams.", (2, 2))
1853
# install the default hooks into the Branch class.
1854
Branch.hooks = BranchHooks()
1857
class ChangeBranchTipParams(object):
1858
"""Object holding parameters passed to `*_change_branch_tip` hooks.
1860
There are 5 fields that hooks may wish to access:
1862
:ivar branch: the branch being changed
1863
:ivar old_revno: revision number before the change
1864
:ivar new_revno: revision number after the change
1865
:ivar old_revid: revision id before the change
1866
:ivar new_revid: revision id after the change
1868
The revid fields are strings. The revno fields are integers.
1871
def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
1872
"""Create a group of ChangeBranchTip parameters.
1874
:param branch: The branch being changed.
1875
:param old_revno: Revision number before the change.
1876
:param new_revno: Revision number after the change.
1877
:param old_revid: Tip revision id before the change.
1878
:param new_revid: Tip revision id after the change.
1880
self.branch = branch
1881
self.old_revno = old_revno
1882
self.new_revno = new_revno
1883
self.old_revid = old_revid
1884
self.new_revid = new_revid
1886
def __eq__(self, other):
1887
return self.__dict__ == other.__dict__
1890
return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1891
self.__class__.__name__, self.branch,
1892
self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1895
class BranchInitHookParams(object):
1896
"""Object holding parameters passed to `*_branch_init` hooks.
1898
There are 4 fields that hooks may wish to access:
1900
:ivar format: the branch format
1901
:ivar bzrdir: the ControlDir where the branch will be/has been initialized
1902
:ivar name: name of colocated branch, if any (or None)
1903
:ivar branch: the branch created
1905
Note that for lightweight checkouts, the bzrdir and format fields refer to
1906
the checkout, hence they are different from the corresponding fields in
1907
branch, which refer to the original branch.
1910
def __init__(self, format, controldir, name, branch):
1911
"""Create a group of BranchInitHook parameters.
1913
:param format: the branch format
1914
:param controldir: the ControlDir where the branch will be/has been
1916
:param name: name of colocated branch, if any (or None)
1917
:param branch: the branch created
1919
Note that for lightweight checkouts, the bzrdir and format fields refer
1920
to the checkout, hence they are different from the corresponding fields
1921
in branch, which refer to the original branch.
1923
self.format = format
1924
self.bzrdir = controldir
1926
self.branch = branch
1928
def __eq__(self, other):
1929
return self.__dict__ == other.__dict__
1932
return "<%s of %s>" % (self.__class__.__name__, self.branch)
1935
class SwitchHookParams(object):
1936
"""Object holding parameters passed to `*_switch` hooks.
1938
There are 4 fields that hooks may wish to access:
1940
:ivar control_dir: ControlDir of the checkout to change
1941
:ivar to_branch: branch that the checkout is to reference
1942
:ivar force: skip the check for local commits in a heavy checkout
1943
:ivar revision_id: revision ID to switch to (or None)
1946
def __init__(self, control_dir, to_branch, force, revision_id):
1947
"""Create a group of SwitchHook parameters.
1949
:param control_dir: ControlDir of the checkout to change
1950
:param to_branch: branch that the checkout is to reference
1951
:param force: skip the check for local commits in a heavy checkout
1952
:param revision_id: revision ID to switch to (or None)
1954
self.control_dir = control_dir
1955
self.to_branch = to_branch
1957
self.revision_id = revision_id
1959
def __eq__(self, other):
1960
return self.__dict__ == other.__dict__
1963
return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1964
self.control_dir, self.to_branch,
1968
class BranchFormatMetadir(bzrdir.BzrFormat, BranchFormat):
1969
"""Base class for branch formats that live in meta directories.
1973
BranchFormat.__init__(self)
1974
bzrdir.BzrFormat.__init__(self)
1977
def find_format(klass, controldir, name=None):
1978
"""Return the format for the branch object in controldir."""
1980
transport = controldir.get_branch_transport(None, name=name)
1981
except errors.NoSuchFile:
1982
raise errors.NotBranchError(path=name, bzrdir=controldir)
1984
format_string = transport.get_bytes("format")
1985
except errors.NoSuchFile:
1986
raise errors.NotBranchError(path=transport.base, bzrdir=controldir)
1987
return klass._find_format(format_registry, 'branch', format_string)
1989
def _branch_class(self):
1990
"""What class to instantiate on open calls."""
1991
raise NotImplementedError(self._branch_class)
1993
def _get_initial_config(self, append_revisions_only=None):
1994
if append_revisions_only:
1995
return "append_revisions_only = True\n"
1997
# Avoid writing anything if append_revisions_only is disabled,
1998
# as that is the default.
2001
def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
2003
"""Initialize a branch in a control dir, with specified files
2005
:param a_bzrdir: The bzrdir to initialize the branch in
2006
:param utf8_files: The files to create as a list of
2007
(filename, content) tuples
2008
:param name: Name of colocated branch to create, if any
2009
:return: a branch in this format
2012
name = a_bzrdir._get_selected_branch()
2013
mutter('creating branch %r in %s', self, a_bzrdir.user_url)
2014
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2015
control_files = lockable_files.LockableFiles(branch_transport,
2016
'lock', lockdir.LockDir)
2017
control_files.create_lock()
2018
control_files.lock_write()
2020
utf8_files += [('format', self.as_string())]
2021
for (filename, content) in utf8_files:
2022
branch_transport.put_bytes(
2024
mode=a_bzrdir._get_file_mode())
2026
control_files.unlock()
2027
branch = self.open(a_bzrdir, name, _found=True,
2028
found_repository=repository)
2029
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2032
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
2033
found_repository=None, possible_transports=None):
2034
"""See BranchFormat.open()."""
2036
name = a_bzrdir._get_selected_branch()
2038
format = BranchFormatMetadir.find_format(a_bzrdir, name=name)
2039
if format.__class__ != self.__class__:
2040
raise AssertionError("wrong format %r found for %r" %
2042
transport = a_bzrdir.get_branch_transport(None, name=name)
2044
control_files = lockable_files.LockableFiles(transport, 'lock',
2046
if found_repository is None:
2047
found_repository = a_bzrdir.find_repository()
2048
return self._branch_class()(_format=self,
2049
_control_files=control_files,
2052
_repository=found_repository,
2053
ignore_fallbacks=ignore_fallbacks,
2054
possible_transports=possible_transports)
2055
except errors.NoSuchFile:
2056
raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
2059
def _matchingbzrdir(self):
2060
ret = bzrdir.BzrDirMetaFormat1()
2061
ret.set_branch_format(self)
2064
def supports_tags(self):
2067
def supports_leaving_lock(self):
2070
def check_support_status(self, allow_unsupported, recommend_upgrade=True,
2072
BranchFormat.check_support_status(self,
2073
allow_unsupported=allow_unsupported, recommend_upgrade=recommend_upgrade,
2075
bzrdir.BzrFormat.check_support_status(self, allow_unsupported=allow_unsupported,
2076
recommend_upgrade=recommend_upgrade, basedir=basedir)
2079
class BzrBranchFormat6(BranchFormatMetadir):
2080
"""Branch format with last-revision and tags.
2082
Unlike previous formats, this has no explicit revision history. Instead,
2083
this just stores the last-revision, and the left-hand history leading
2084
up to there is the history.
2086
This format was introduced in bzr 0.15
2087
and became the default in 0.91.
2090
def _branch_class(self):
2094
def get_format_string(cls):
2095
"""See BranchFormat.get_format_string()."""
2096
return "Bazaar Branch Format 6 (bzr 0.15)\n"
2098
def get_format_description(self):
2099
"""See BranchFormat.get_format_description()."""
2100
return "Branch format 6"
2102
def initialize(self, a_bzrdir, name=None, repository=None,
2103
append_revisions_only=None):
2104
"""Create a branch of this format in a_bzrdir."""
2105
utf8_files = [('last-revision', '0 null:\n'),
2107
self._get_initial_config(append_revisions_only)),
2110
return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2112
def make_tags(self, branch):
2113
"""See bzrlib.branch.BranchFormat.make_tags()."""
2114
return _mod_tag.BasicTags(branch)
2116
def supports_set_append_revisions_only(self):
2120
class BzrBranchFormat8(BranchFormatMetadir):
2121
"""Metadir format supporting storing locations of subtree branches."""
2123
def _branch_class(self):
2127
def get_format_string(cls):
2128
"""See BranchFormat.get_format_string()."""
2129
return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
2131
def get_format_description(self):
2132
"""See BranchFormat.get_format_description()."""
2133
return "Branch format 8"
2135
def initialize(self, a_bzrdir, name=None, repository=None,
2136
append_revisions_only=None):
2137
"""Create a branch of this format in a_bzrdir."""
2138
utf8_files = [('last-revision', '0 null:\n'),
2140
self._get_initial_config(append_revisions_only)),
2144
return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2146
def make_tags(self, branch):
2147
"""See bzrlib.branch.BranchFormat.make_tags()."""
2148
return _mod_tag.BasicTags(branch)
2150
def supports_set_append_revisions_only(self):
2153
def supports_stacking(self):
2156
supports_reference_locations = True
2159
class BzrBranchFormat7(BranchFormatMetadir):
2160
"""Branch format with last-revision, tags, and a stacked location pointer.
2162
The stacked location pointer is passed down to the repository and requires
2163
a repository format with supports_external_lookups = True.
2165
This format was introduced in bzr 1.6.
2168
def initialize(self, a_bzrdir, name=None, repository=None,
2169
append_revisions_only=None):
2170
"""Create a branch of this format in a_bzrdir."""
2171
utf8_files = [('last-revision', '0 null:\n'),
2173
self._get_initial_config(append_revisions_only)),
2176
return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2178
def _branch_class(self):
2182
def get_format_string(cls):
2183
"""See BranchFormat.get_format_string()."""
2184
return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
2186
def get_format_description(self):
2187
"""See BranchFormat.get_format_description()."""
2188
return "Branch format 7"
2190
def supports_set_append_revisions_only(self):
2193
def supports_stacking(self):
2196
def make_tags(self, branch):
2197
"""See bzrlib.branch.BranchFormat.make_tags()."""
2198
return _mod_tag.BasicTags(branch)
2200
supports_reference_locations = False
2203
class BranchReferenceFormat(BranchFormatMetadir):
2204
"""Bzr branch reference format.
2206
Branch references are used in implementing checkouts, they
2207
act as an alias to the real branch which is at some other url.
2215
def get_format_string(cls):
2216
"""See BranchFormat.get_format_string()."""
2217
return "Bazaar-NG Branch Reference Format 1\n"
2219
def get_format_description(self):
2220
"""See BranchFormat.get_format_description()."""
2221
return "Checkout reference format 1"
2223
def get_reference(self, a_bzrdir, name=None):
2224
"""See BranchFormat.get_reference()."""
2225
transport = a_bzrdir.get_branch_transport(None, name=name)
2226
return transport.get_bytes('location')
2228
def set_reference(self, a_bzrdir, name, to_branch):
2229
"""See BranchFormat.set_reference()."""
2230
transport = a_bzrdir.get_branch_transport(None, name=name)
2231
location = transport.put_bytes('location', to_branch.base)
2233
def initialize(self, a_bzrdir, name=None, target_branch=None,
2234
repository=None, append_revisions_only=None):
2235
"""Create a branch of this format in a_bzrdir."""
2236
if target_branch is None:
2237
# this format does not implement branch itself, thus the implicit
2238
# creation contract must see it as uninitializable
2239
raise errors.UninitializableFormat(self)
2240
mutter('creating branch reference in %s', a_bzrdir.user_url)
2241
if a_bzrdir._format.fixed_components:
2242
raise errors.IncompatibleFormat(self, a_bzrdir._format)
2244
name = a_bzrdir._get_selected_branch()
2245
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2246
branch_transport.put_bytes('location',
2247
target_branch.user_url)
2248
branch_transport.put_bytes('format', self.as_string())
2249
branch = self.open(a_bzrdir, name, _found=True,
2250
possible_transports=[target_branch.bzrdir.root_transport])
2251
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2254
def _make_reference_clone_function(format, a_branch):
2255
"""Create a clone() routine for a branch dynamically."""
2256
def clone(to_bzrdir, revision_id=None,
2257
repository_policy=None):
2258
"""See Branch.clone()."""
2259
return format.initialize(to_bzrdir, target_branch=a_branch)
2260
# cannot obey revision_id limits when cloning a reference ...
2261
# FIXME RBC 20060210 either nuke revision_id for clone, or
2262
# emit some sort of warning/error to the caller ?!
2265
def open(self, a_bzrdir, name=None, _found=False, location=None,
2266
possible_transports=None, ignore_fallbacks=False,
2267
found_repository=None):
2268
"""Return the branch that the branch reference in a_bzrdir points at.
2270
:param a_bzrdir: A BzrDir that contains a branch.
2271
:param name: Name of colocated branch to open, if any
2272
:param _found: a private parameter, do not use it. It is used to
2273
indicate if format probing has already be done.
2274
:param ignore_fallbacks: when set, no fallback branches will be opened
2275
(if there are any). Default is to open fallbacks.
2276
:param location: The location of the referenced branch. If
2277
unspecified, this will be determined from the branch reference in
2279
:param possible_transports: An optional reusable transports list.
2282
name = a_bzrdir._get_selected_branch()
2284
format = BranchFormatMetadir.find_format(a_bzrdir, name=name)
2285
if format.__class__ != self.__class__:
2286
raise AssertionError("wrong format %r found for %r" %
2288
if location is None:
2289
location = self.get_reference(a_bzrdir, name)
2290
real_bzrdir = controldir.ControlDir.open(
2291
location, possible_transports=possible_transports)
2292
result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks,
2293
possible_transports=possible_transports)
2294
# this changes the behaviour of result.clone to create a new reference
2295
# rather than a copy of the content of the branch.
2296
# I did not use a proxy object because that needs much more extensive
2297
# testing, and we are only changing one behaviour at the moment.
2298
# If we decide to alter more behaviours - i.e. the implicit nickname
2299
# then this should be refactored to introduce a tested proxy branch
2300
# and a subclass of that for use in overriding clone() and ....
2302
result.clone = self._make_reference_clone_function(result)
2306
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
2307
"""Branch format registry."""
2309
def __init__(self, other_registry=None):
2310
super(BranchFormatRegistry, self).__init__(other_registry)
2311
self._default_format = None
2313
def set_default(self, format):
2314
self._default_format = format
2316
def get_default(self):
2317
return self._default_format
2320
network_format_registry = registry.FormatRegistry()
2321
"""Registry of formats indexed by their network name.
2323
The network name for a branch format is an identifier that can be used when
2324
referring to formats with smart server operations. See
2325
BranchFormat.network_name() for more detail.
2328
format_registry = BranchFormatRegistry(network_format_registry)
2331
# formats which have no format string are not discoverable
2332
# and not independently creatable, so are not registered.
2333
__format6 = BzrBranchFormat6()
2334
__format7 = BzrBranchFormat7()
2335
__format8 = BzrBranchFormat8()
2336
format_registry.register_lazy(
2337
"Bazaar-NG branch format 5\n", "bzrlib.branchfmt.fullhistory", "BzrBranchFormat5")
2338
format_registry.register(BranchReferenceFormat())
2339
format_registry.register(__format6)
2340
format_registry.register(__format7)
2341
format_registry.register(__format8)
2342
format_registry.set_default(__format7)
2345
class BranchWriteLockResult(LogicalLockResult):
2346
"""The result of write locking a branch.
2348
:ivar branch_token: The token obtained from the underlying branch lock, or
2350
:ivar unlock: A callable which will unlock the lock.
2353
def __init__(self, unlock, branch_token):
2354
LogicalLockResult.__init__(self, unlock)
2355
self.branch_token = branch_token
2358
return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2362
class BzrBranch(Branch, _RelockDebugMixin):
2363
"""A branch stored in the actual filesystem.
2365
Note that it's "local" in the context of the filesystem; it doesn't
2366
really matter if it's on an nfs/smb/afs/coda/... share, as long as
2367
it's writable, and can be accessed via the normal filesystem API.
2369
:ivar _transport: Transport for file operations on this branch's
2370
control files, typically pointing to the .bzr/branch directory.
2371
:ivar repository: Repository for this branch.
2372
:ivar base: The url of the base directory for this branch; the one
2373
containing the .bzr directory.
2374
:ivar name: Optional colocated branch name as it exists in the control
2378
def __init__(self, _format=None,
2379
_control_files=None, a_bzrdir=None, name=None,
2380
_repository=None, ignore_fallbacks=False,
2381
possible_transports=None):
2382
"""Create new branch object at a particular location."""
2383
if a_bzrdir is None:
2384
raise ValueError('a_bzrdir must be supplied')
2386
raise ValueError('name must be supplied')
2387
self.bzrdir = a_bzrdir
2388
self._user_transport = self.bzrdir.transport.clone('..')
2390
self._user_transport.set_segment_parameter(
2391
"branch", urlutils.escape(name))
2392
self._base = self._user_transport.base
2394
self._format = _format
2395
if _control_files is None:
2396
raise ValueError('BzrBranch _control_files is None')
2397
self.control_files = _control_files
2398
self._transport = _control_files._transport
2399
self.repository = _repository
2400
self.conf_store = None
2401
Branch.__init__(self, possible_transports)
2404
return '%s(%s)' % (self.__class__.__name__, self.user_url)
2408
def _get_base(self):
2409
"""Returns the directory containing the control directory."""
2412
base = property(_get_base, doc="The URL for the root of this branch.")
2415
def user_transport(self):
2416
return self._user_transport
2418
def _get_config(self):
2419
return _mod_config.TransportConfig(self._transport, 'branch.conf')
2421
def _get_config_store(self):
2422
if self.conf_store is None:
2423
self.conf_store = _mod_config.BranchStore(self)
2424
return self.conf_store
2426
def _get_uncommitted(self):
2427
"""Return a serialized TreeTransform for uncommitted changes.
2429
:return: a file-like object containing a serialized TreeTransform or
2430
None if no uncommitted changes are stored.
2433
return self._transport.get('stored-transform')
2434
except errors.NoSuchFile:
2437
def _put_uncommitted(self, transform):
2438
"""Store a serialized TreeTransform for uncommitted changes.
2440
:param input: a file-like object.
2442
if transform is None:
2444
self._transport.delete('stored-transform')
2445
except errors.NoSuchFile:
2448
self._transport.put_file('stored-transform', transform)
2450
def is_locked(self):
2451
return self.control_files.is_locked()
2453
def lock_write(self, token=None):
2454
"""Lock the branch for write operations.
2456
:param token: A token to permit reacquiring a previously held and
2458
:return: A BranchWriteLockResult.
2460
if not self.is_locked():
2461
self._note_lock('w')
2462
self.repository._warn_if_deprecated(self)
2463
self.repository.lock_write()
2468
return BranchWriteLockResult(self.unlock,
2469
self.control_files.lock_write(token=token))
2472
self.repository.unlock()
2475
def lock_read(self):
2476
"""Lock the branch for read operations.
2478
:return: A bzrlib.lock.LogicalLockResult.
2480
if not self.is_locked():
2481
self._note_lock('r')
2482
self.repository._warn_if_deprecated(self)
2483
self.repository.lock_read()
2488
self.control_files.lock_read()
2489
return LogicalLockResult(self.unlock)
2492
self.repository.unlock()
2495
@only_raises(errors.LockNotHeld, errors.LockBroken)
2497
if self.control_files._lock_count == 1 and self.conf_store is not None:
2498
self.conf_store.save_changes()
2500
self.control_files.unlock()
2502
if not self.control_files.is_locked():
2503
self.repository.unlock()
2504
# we just released the lock
2505
self._clear_cached_state()
2507
def peek_lock_mode(self):
2508
if self.control_files._lock_count == 0:
2511
return self.control_files._lock_mode
2513
def get_physical_lock_status(self):
2514
return self.control_files.get_physical_lock_status()
2517
def print_file(self, file, revision_id):
2518
"""See Branch.print_file."""
2519
return self.repository.print_file(file, revision_id)
2522
def set_last_revision_info(self, revno, revision_id):
2523
if not revision_id or not isinstance(revision_id, basestring):
2524
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2525
revision_id = _mod_revision.ensure_null(revision_id)
2526
old_revno, old_revid = self.last_revision_info()
2527
if self.get_append_revisions_only():
2528
self._check_history_violation(revision_id)
2529
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2530
self._write_last_revision_info(revno, revision_id)
2531
self._clear_cached_state()
2532
self._last_revision_info_cache = revno, revision_id
2533
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2535
def basis_tree(self):
2536
"""See Branch.basis_tree."""
2537
return self.repository.revision_tree(self.last_revision())
2539
def _get_parent_location(self):
2540
_locs = ['parent', 'pull', 'x-pull']
2543
return self._transport.get_bytes(l).strip('\n')
2544
except errors.NoSuchFile:
2548
def get_stacked_on_url(self):
2549
raise errors.UnstackableBranchFormat(self._format, self.user_url)
2551
def set_push_location(self, location):
2552
"""See Branch.set_push_location."""
2553
self.get_config().set_user_option(
2554
'push_location', location,
2555
store=_mod_config.STORE_LOCATION_NORECURSE)
2557
def _set_parent_location(self, url):
2559
self._transport.delete('parent')
2561
self._transport.put_bytes('parent', url + '\n',
2562
mode=self.bzrdir._get_file_mode())
2566
"""If bound, unbind"""
2567
return self.set_bound_location(None)
2570
def bind(self, other):
2571
"""Bind this branch to the branch other.
2573
This does not push or pull data between the branches, though it does
2574
check for divergence to raise an error when the branches are not
2575
either the same, or one a prefix of the other. That behaviour may not
2576
be useful, so that check may be removed in future.
2578
:param other: The branch to bind to
2581
# TODO: jam 20051230 Consider checking if the target is bound
2582
# It is debatable whether you should be able to bind to
2583
# a branch which is itself bound.
2584
# Committing is obviously forbidden,
2585
# but binding itself may not be.
2586
# Since we *have* to check at commit time, we don't
2587
# *need* to check here
2589
# we want to raise diverged if:
2590
# last_rev is not in the other_last_rev history, AND
2591
# other_last_rev is not in our history, and do it without pulling
2593
self.set_bound_location(other.base)
2595
def get_bound_location(self):
2597
return self._transport.get_bytes('bound')[:-1]
2598
except errors.NoSuchFile:
2602
def get_master_branch(self, possible_transports=None):
2603
"""Return the branch we are bound to.
2605
:return: Either a Branch, or None
2607
if self._master_branch_cache is None:
2608
self._master_branch_cache = self._get_master_branch(
2609
possible_transports)
2610
return self._master_branch_cache
2612
def _get_master_branch(self, possible_transports):
2613
bound_loc = self.get_bound_location()
2617
return Branch.open(bound_loc,
2618
possible_transports=possible_transports)
2619
except (errors.NotBranchError, errors.ConnectionError), e:
2620
raise errors.BoundBranchConnectionFailure(
2624
def set_bound_location(self, location):
2625
"""Set the target where this branch is bound to.
2627
:param location: URL to the target branch
2629
self._master_branch_cache = None
2631
self._transport.put_bytes('bound', location+'\n',
2632
mode=self.bzrdir._get_file_mode())
2635
self._transport.delete('bound')
2636
except errors.NoSuchFile:
2641
def update(self, possible_transports=None):
2642
"""Synchronise this branch with the master branch if any.
2644
:return: None or the last_revision that was pivoted out during the
2647
master = self.get_master_branch(possible_transports)
2648
if master is not None:
2649
old_tip = _mod_revision.ensure_null(self.last_revision())
2650
self.pull(master, overwrite=True)
2651
if self.repository.get_graph().is_ancestor(old_tip,
2652
_mod_revision.ensure_null(self.last_revision())):
2657
def _read_last_revision_info(self):
2658
revision_string = self._transport.get_bytes('last-revision')
2659
revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2660
revision_id = cache_utf8.get_cached_utf8(revision_id)
2662
return revno, revision_id
2664
def _write_last_revision_info(self, revno, revision_id):
2665
"""Simply write out the revision id, with no checks.
2667
Use set_last_revision_info to perform this safely.
2669
Does not update the revision_history cache.
2671
revision_id = _mod_revision.ensure_null(revision_id)
2672
out_string = '%d %s\n' % (revno, revision_id)
2673
self._transport.put_bytes('last-revision', out_string,
2674
mode=self.bzrdir._get_file_mode())
2677
def update_feature_flags(self, updated_flags):
2678
"""Update the feature flags for this branch.
2680
:param updated_flags: Dictionary mapping feature names to necessities
2681
A necessity can be None to indicate the feature should be removed
2683
self._format._update_feature_flags(updated_flags)
2684
self.control_transport.put_bytes('format', self._format.as_string())
2687
class BzrBranch8(BzrBranch):
2688
"""A branch that stores tree-reference locations."""
2690
def _open_hook(self, possible_transports=None):
2691
if self._ignore_fallbacks:
2693
if possible_transports is None:
2694
possible_transports = [self.bzrdir.root_transport]
2696
url = self.get_stacked_on_url()
2697
except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2698
errors.UnstackableBranchFormat):
898
revs = self.revision_history()
899
if isinstance(revision, int):
902
# Mabye we should do this first, but we don't need it if revision == 0
904
revno = len(revs) + revision + 1
907
elif isinstance(revision, basestring):
908
for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
909
if revision.startswith(prefix):
910
revno = func(self, revs, revision)
913
raise BzrError('No namespace registered for string: %r' % revision)
915
if revno is None or revno <= 0 or revno > len(revs):
916
raise BzrError("no such revision %s" % revision)
917
return revno, revs[revno-1]
919
def _namespace_revno(self, revs, revision):
920
"""Lookup a revision by revision number"""
921
assert revision.startswith('revno:')
923
return int(revision[6:])
926
REVISION_NAMESPACES['revno:'] = _namespace_revno
928
def _namespace_revid(self, revs, revision):
929
assert revision.startswith('revid:')
931
return revs.index(revision[6:]) + 1
934
REVISION_NAMESPACES['revid:'] = _namespace_revid
936
def _namespace_last(self, revs, revision):
937
assert revision.startswith('last:')
939
offset = int(revision[5:])
944
raise BzrError('You must supply a positive value for --revision last:XXX')
945
return len(revs) - offset + 1
946
REVISION_NAMESPACES['last:'] = _namespace_last
948
def _namespace_tag(self, revs, revision):
949
assert revision.startswith('tag:')
950
raise BzrError('tag: namespace registered, but not implemented.')
951
REVISION_NAMESPACES['tag:'] = _namespace_tag
953
def _namespace_date(self, revs, revision):
954
assert revision.startswith('date:')
956
# Spec for date revisions:
958
# value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
959
# it can also start with a '+/-/='. '+' says match the first
960
# entry after the given date. '-' is match the first entry before the date
961
# '=' is match the first entry after, but still on the given date.
963
# +2005-05-12 says find the first matching entry after May 12th, 2005 at 0:00
964
# -2005-05-12 says find the first matching entry before May 12th, 2005 at 0:00
965
# =2005-05-12 says find the first match after May 12th, 2005 at 0:00 but before
966
# May 13th, 2005 at 0:00
968
# So the proper way of saying 'give me all entries for today' is:
969
# -r {date:+today}:{date:-tomorrow}
970
# The default is '=' when not supplied
973
if val[:1] in ('+', '-', '='):
974
match_style = val[:1]
977
today = datetime.datetime.today().replace(hour=0,minute=0,second=0,microsecond=0)
978
if val.lower() == 'yesterday':
979
dt = today - datetime.timedelta(days=1)
980
elif val.lower() == 'today':
982
elif val.lower() == 'tomorrow':
983
dt = today + datetime.timedelta(days=1)
986
# This should be done outside the function to avoid recompiling it.
987
_date_re = re.compile(
988
r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
990
r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
992
m = _date_re.match(val)
993
if not m or (not m.group('date') and not m.group('time')):
994
raise BzrError('Invalid revision date %r' % revision)
997
year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
999
year, month, day = today.year, today.month, today.day
1001
hour = int(m.group('hour'))
1002
minute = int(m.group('minute'))
1003
if m.group('second'):
1004
second = int(m.group('second'))
1008
hour, minute, second = 0,0,0
1010
dt = datetime.datetime(year=year, month=month, day=day,
1011
hour=hour, minute=minute, second=second)
1015
if match_style == '-':
1017
elif match_style == '=':
1018
last = dt + datetime.timedelta(days=1)
1021
for i in range(len(revs)-1, -1, -1):
1022
r = self.get_revision(revs[i])
1023
# TODO: Handle timezone.
1024
dt = datetime.datetime.fromtimestamp(r.timestamp)
1025
if first >= dt and (last is None or dt >= last):
1028
for i in range(len(revs)):
1029
r = self.get_revision(revs[i])
1030
# TODO: Handle timezone.
1031
dt = datetime.datetime.fromtimestamp(r.timestamp)
1032
if first <= dt and (last is None or dt <= last):
1034
REVISION_NAMESPACES['date:'] = _namespace_date
1036
def revision_tree(self, revision_id):
1037
"""Return Tree for a revision on this branch.
1039
`revision_id` may be None for the null revision, in which case
1040
an `EmptyTree` is returned."""
1041
# TODO: refactor this to use an existing revision object
1042
# so we don't need to read it in twice.
1043
if revision_id == None:
1046
inv = self.get_revision_inventory(revision_id)
1047
return RevisionTree(self.text_store, inv)
1050
def working_tree(self):
1051
"""Return a `Tree` for the working copy."""
1052
from workingtree import WorkingTree
1053
return WorkingTree(self.base, self.read_working_inventory())
1056
def basis_tree(self):
1057
"""Return `Tree` object for last revision.
1059
If there are no revisions yet, return an `EmptyTree`.
1061
r = self.last_patch()
1065
return RevisionTree(self.text_store, self.get_revision_inventory(r))
1069
def rename_one(self, from_rel, to_rel):
1072
This can change the directory or the filename or both.
1076
tree = self.working_tree()
1077
inv = tree.inventory
1078
if not tree.has_filename(from_rel):
1079
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
1080
if tree.has_filename(to_rel):
1081
raise BzrError("can't rename: new working file %r already exists" % to_rel)
1083
file_id = inv.path2id(from_rel)
1085
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
1087
if inv.path2id(to_rel):
1088
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
1090
to_dir, to_tail = os.path.split(to_rel)
1091
to_dir_id = inv.path2id(to_dir)
1092
if to_dir_id == None and to_dir != '':
1093
raise BzrError("can't determine destination directory id for %r" % to_dir)
1095
mutter("rename_one:")
1096
mutter(" file_id {%s}" % file_id)
1097
mutter(" from_rel %r" % from_rel)
1098
mutter(" to_rel %r" % to_rel)
1099
mutter(" to_dir %r" % to_dir)
1100
mutter(" to_dir_id {%s}" % to_dir_id)
1102
inv.rename(file_id, to_dir_id, to_tail)
1104
print "%s => %s" % (from_rel, to_rel)
1106
from_abs = self.abspath(from_rel)
1107
to_abs = self.abspath(to_rel)
1109
os.rename(from_abs, to_abs)
1111
raise BzrError("failed to rename %r to %r: %s"
1112
% (from_abs, to_abs, e[1]),
1113
["rename rolled back"])
1115
self._write_inventory(inv)
1120
def move(self, from_paths, to_name):
1123
to_name must exist as a versioned directory.
1125
If to_name exists and is a directory, the files are moved into
1126
it, keeping their old names. If it is a directory,
1128
Note that to_name is only the last component of the new name;
1129
this doesn't change the directory.
1133
## TODO: Option to move IDs only
1134
assert not isinstance(from_paths, basestring)
1135
tree = self.working_tree()
1136
inv = tree.inventory
1137
to_abs = self.abspath(to_name)
1138
if not isdir(to_abs):
1139
raise BzrError("destination %r is not a directory" % to_abs)
1140
if not tree.has_filename(to_name):
1141
raise BzrError("destination %r not in working directory" % to_abs)
1142
to_dir_id = inv.path2id(to_name)
1143
if to_dir_id == None and to_name != '':
1144
raise BzrError("destination %r is not a versioned directory" % to_name)
1145
to_dir_ie = inv[to_dir_id]
1146
if to_dir_ie.kind not in ('directory', 'root_directory'):
1147
raise BzrError("destination %r is not a directory" % to_abs)
1149
to_idpath = inv.get_idpath(to_dir_id)
1151
for f in from_paths:
1152
if not tree.has_filename(f):
1153
raise BzrError("%r does not exist in working tree" % f)
1154
f_id = inv.path2id(f)
1156
raise BzrError("%r is not versioned" % f)
1157
name_tail = splitpath(f)[-1]
1158
dest_path = appendpath(to_name, name_tail)
1159
if tree.has_filename(dest_path):
1160
raise BzrError("destination %r already exists" % dest_path)
1161
if f_id in to_idpath:
1162
raise BzrError("can't move %r to a subdirectory of itself" % f)
1164
# OK, so there's a race here, it's possible that someone will
1165
# create a file in this interval and then the rename might be
1166
# left half-done. But we should have caught most problems.
1168
for f in from_paths:
1169
name_tail = splitpath(f)[-1]
1170
dest_path = appendpath(to_name, name_tail)
1171
print "%s => %s" % (f, dest_path)
1172
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1174
os.rename(self.abspath(f), self.abspath(dest_path))
1176
raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1177
["rename rolled back"])
1179
self._write_inventory(inv)
1184
def revert(self, filenames, old_tree=None, backups=True):
1185
"""Restore selected files to the versions from a previous tree.
1188
If true (default) backups are made of files before
1191
from bzrlib.errors import NotVersionedError, BzrError
1192
from bzrlib.atomicfile import AtomicFile
1193
from bzrlib.osutils import backup_file
2701
for hook in Branch.hooks['transform_fallback_location']:
2702
url = hook(self, url)
2704
hook_name = Branch.hooks.get_hook_name(hook)
2705
raise AssertionError(
2706
"'transform_fallback_location' hook %s returned "
2707
"None, not a URL." % hook_name)
2708
self._activate_fallback_location(url,
2709
possible_transports=possible_transports)
2711
def __init__(self, *args, **kwargs):
2712
self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2713
super(BzrBranch8, self).__init__(*args, **kwargs)
2714
self._last_revision_info_cache = None
2715
self._reference_info = None
2717
def _clear_cached_state(self):
2718
super(BzrBranch8, self)._clear_cached_state()
2719
self._last_revision_info_cache = None
2720
self._reference_info = None
2722
def _check_history_violation(self, revision_id):
2723
current_revid = self.last_revision()
2724
last_revision = _mod_revision.ensure_null(current_revid)
2725
if _mod_revision.is_null(last_revision):
2727
graph = self.repository.get_graph()
2728
for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
2729
if lh_ancestor == current_revid:
2731
raise errors.AppendRevisionsOnlyViolation(self.user_url)
2733
def _gen_revision_history(self):
2734
"""Generate the revision history from last revision
2736
last_revno, last_revision = self.last_revision_info()
2737
self._extend_partial_history(stop_index=last_revno-1)
2738
return list(reversed(self._partial_revision_history_cache))
2741
def _set_parent_location(self, url):
2742
"""Set the parent branch"""
2743
self._set_config_location('parent_location', url, make_relative=True)
2746
def _get_parent_location(self):
2747
"""Set the parent branch"""
2748
return self._get_config_location('parent_location')
2751
def _set_all_reference_info(self, info_dict):
2752
"""Replace all reference info stored in a branch.
2754
:param info_dict: A dict of {file_id: (tree_path, branch_location)}
2757
writer = rio.RioWriter(s)
2758
for key, (tree_path, branch_location) in info_dict.iteritems():
2759
stanza = rio.Stanza(file_id=key, tree_path=tree_path,
2760
branch_location=branch_location)
2761
writer.write_stanza(stanza)
2762
self._transport.put_bytes('references', s.getvalue())
2763
self._reference_info = info_dict
2766
def _get_all_reference_info(self):
2767
"""Return all the reference info stored in a branch.
2769
:return: A dict of {file_id: (tree_path, branch_location)}
2771
if self._reference_info is not None:
2772
return self._reference_info
2773
rio_file = self._transport.get('references')
2775
stanzas = rio.read_stanzas(rio_file)
2776
info_dict = dict((s['file_id'], (s['tree_path'],
2777
s['branch_location'])) for s in stanzas)
2780
self._reference_info = info_dict
2783
def set_reference_info(self, file_id, tree_path, branch_location):
2784
"""Set the branch location to use for a tree reference.
2786
:param file_id: The file-id of the tree reference.
2787
:param tree_path: The path of the tree reference in the tree.
2788
:param branch_location: The location of the branch to retrieve tree
2791
info_dict = self._get_all_reference_info()
2792
info_dict[file_id] = (tree_path, branch_location)
2793
if None in (tree_path, branch_location):
2794
if tree_path is not None:
2795
raise ValueError('tree_path must be None when branch_location'
2797
if branch_location is not None:
2798
raise ValueError('branch_location must be None when tree_path'
2800
del info_dict[file_id]
2801
self._set_all_reference_info(info_dict)
2803
def get_reference_info(self, file_id):
2804
"""Get the tree_path and branch_location for a tree reference.
2806
:return: a tuple of (tree_path, branch_location)
2808
return self._get_all_reference_info().get(file_id, (None, None))
2810
def reference_parent(self, file_id, path, possible_transports=None):
2811
"""Return the parent branch for a tree-reference file_id.
2813
:param file_id: The file_id of the tree reference
2814
:param path: The path of the file_id in the tree
2815
:return: A branch associated with the file_id
2817
branch_location = self.get_reference_info(file_id)[1]
2818
if branch_location is None:
2819
return Branch.reference_parent(self, file_id, path,
2820
possible_transports)
2821
branch_location = urlutils.join(self.user_url, branch_location)
2822
return Branch.open(branch_location,
2823
possible_transports=possible_transports)
2825
def set_push_location(self, location):
2826
"""See Branch.set_push_location."""
2827
self._set_config_location('push_location', location)
2829
def set_bound_location(self, location):
2830
"""See Branch.set_push_location."""
2831
self._master_branch_cache = None
2833
conf = self.get_config_stack()
2834
if location is None:
2835
if not conf.get('bound'):
2838
conf.set('bound', 'False')
2841
self._set_config_location('bound_location', location,
2843
conf.set('bound', 'True')
2846
def _get_bound_location(self, bound):
2847
"""Return the bound location in the config file.
2849
Return None if the bound parameter does not match"""
2850
conf = self.get_config_stack()
2851
if conf.get('bound') != bound:
2853
return self._get_config_location('bound_location', config=conf)
2855
def get_bound_location(self):
2856
"""See Branch.get_bound_location."""
2857
return self._get_bound_location(True)
2859
def get_old_bound_location(self):
2860
"""See Branch.get_old_bound_location"""
2861
return self._get_bound_location(False)
2863
def get_stacked_on_url(self):
2864
# you can always ask for the URL; but you might not be able to use it
2865
# if the repo can't support stacking.
2866
## self._check_stackable_repo()
2867
# stacked_on_location is only ever defined in branch.conf, so don't
2868
# waste effort reading the whole stack of config files.
2869
conf = _mod_config.BranchOnlyStack(self)
2870
stacked_url = self._get_config_location('stacked_on_location',
2872
if stacked_url is None:
2873
raise errors.NotStacked(self)
2874
return stacked_url.encode('utf-8')
2877
def get_rev_id(self, revno, history=None):
2878
"""Find the revision id of the specified revno."""
2880
return _mod_revision.NULL_REVISION
2882
last_revno, last_revision_id = self.last_revision_info()
2883
if revno <= 0 or revno > last_revno:
2884
raise errors.NoSuchRevision(self, revno)
2886
if history is not None:
2887
return history[revno - 1]
2889
index = last_revno - revno
2890
if len(self._partial_revision_history_cache) <= index:
2891
self._extend_partial_history(stop_index=index)
2892
if len(self._partial_revision_history_cache) > index:
2893
return self._partial_revision_history_cache[index]
2895
raise errors.NoSuchRevision(self, revno)
2898
def revision_id_to_revno(self, revision_id):
2899
"""Given a revision id, return its revno"""
2900
if _mod_revision.is_null(revision_id):
2903
index = self._partial_revision_history_cache.index(revision_id)
2906
self._extend_partial_history(stop_revision=revision_id)
2907
except errors.RevisionNotPresent, e:
2908
raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
2909
index = len(self._partial_revision_history_cache) - 1
2911
raise errors.NoSuchRevision(self, revision_id)
2912
if self._partial_revision_history_cache[index] != revision_id:
2913
raise errors.NoSuchRevision(self, revision_id)
2914
return self.revno() - index
2917
class BzrBranch7(BzrBranch8):
2918
"""A branch with support for a fallback repository."""
2920
def set_reference_info(self, file_id, tree_path, branch_location):
2921
Branch.set_reference_info(self, file_id, tree_path, branch_location)
2923
def get_reference_info(self, file_id):
2924
Branch.get_reference_info(self, file_id)
2926
def reference_parent(self, file_id, path, possible_transports=None):
2927
return Branch.reference_parent(self, file_id, path,
2928
possible_transports)
2931
class BzrBranch6(BzrBranch7):
2932
"""See BzrBranchFormat6 for the capabilities of this branch.
2934
This subclass of BzrBranch7 disables the new features BzrBranch7 added,
2938
def get_stacked_on_url(self):
2939
raise errors.UnstackableBranchFormat(self._format, self.user_url)
2942
######################################################################
2943
# results of operations
2946
class _Result(object):
2948
def _show_tag_conficts(self, to_file):
2949
if not getattr(self, 'tag_conflicts', None):
2951
to_file.write('Conflicting tags:\n')
2952
for name, value1, value2 in self.tag_conflicts:
2953
to_file.write(' %s\n' % (name, ))
2956
class PullResult(_Result):
2957
"""Result of a Branch.pull operation.
2959
:ivar old_revno: Revision number before pull.
2960
:ivar new_revno: Revision number after pull.
2961
:ivar old_revid: Tip revision id before pull.
2962
:ivar new_revid: Tip revision id after pull.
2963
:ivar source_branch: Source (local) branch object. (read locked)
2964
:ivar master_branch: Master branch of the target, or the target if no
2966
:ivar local_branch: target branch if there is a Master, else None
2967
:ivar target_branch: Target/destination branch object. (write locked)
2968
:ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2969
:ivar tag_updates: A dict with new tags, see BasicTags.merge_to
2972
def report(self, to_file):
2973
tag_conflicts = getattr(self, "tag_conflicts", None)
2974
tag_updates = getattr(self, "tag_updates", None)
2976
if self.old_revid != self.new_revid:
2977
to_file.write('Now on revision %d.\n' % self.new_revno)
2979
to_file.write('%d tag(s) updated.\n' % len(tag_updates))
2980
if self.old_revid == self.new_revid and not tag_updates:
2981
if not tag_conflicts:
2982
to_file.write('No revisions or tags to pull.\n')
2984
to_file.write('No revisions to pull.\n')
2985
self._show_tag_conficts(to_file)
2988
class BranchPushResult(_Result):
2989
"""Result of a Branch.push operation.
2991
:ivar old_revno: Revision number (eg 10) of the target before push.
2992
:ivar new_revno: Revision number (eg 12) of the target after push.
2993
:ivar old_revid: Tip revision id (eg joe@foo.com-1234234-aoeua34) of target
2995
:ivar new_revid: Tip revision id (eg joe@foo.com-5676566-boa234a) of target
2997
:ivar source_branch: Source branch object that the push was from. This is
2998
read locked, and generally is a local (and thus low latency) branch.
2999
:ivar master_branch: If target is a bound branch, the master branch of
3000
target, or target itself. Always write locked.
3001
:ivar target_branch: The direct Branch where data is being sent (write
3003
:ivar local_branch: If the target is a bound branch this will be the
3004
target, otherwise it will be None.
3007
def report(self, to_file):
3008
# TODO: This function gets passed a to_file, but then
3009
# ignores it and calls note() instead. This is also
3010
# inconsistent with PullResult(), which writes to stdout.
3011
# -- JRV20110901, bug #838853
3012
tag_conflicts = getattr(self, "tag_conflicts", None)
3013
tag_updates = getattr(self, "tag_updates", None)
3015
if self.old_revid != self.new_revid:
3016
note(gettext('Pushed up to revision %d.') % self.new_revno)
3018
note(ngettext('%d tag updated.', '%d tags updated.', len(tag_updates)) % len(tag_updates))
3019
if self.old_revid == self.new_revid and not tag_updates:
3020
if not tag_conflicts:
3021
note(gettext('No new revisions or tags to push.'))
3023
note(gettext('No new revisions to push.'))
3024
self._show_tag_conficts(to_file)
3027
class BranchCheckResult(object):
3028
"""Results of checking branch consistency.
3033
def __init__(self, branch):
3034
self.branch = branch
3037
def report_results(self, verbose):
3038
"""Report the check results via trace.note.
3040
:param verbose: Requests more detailed display of what was checked,
3043
note(gettext('checked branch {0} format {1}').format(
3044
self.branch.user_url, self.branch._format))
3045
for error in self.errors:
3046
note(gettext('found error:%s'), error)
3049
class Converter5to6(object):
3050
"""Perform an in-place upgrade of format 5 to format 6"""
3052
def convert(self, branch):
3053
# Data for 5 and 6 can peacefully coexist.
3054
format = BzrBranchFormat6()
3055
new_branch = format.open(branch.bzrdir, _found=True)
3057
# Copy source data into target
3058
new_branch._write_last_revision_info(*branch.last_revision_info())
3059
new_branch.lock_write()
3061
new_branch.set_parent(branch.get_parent())
3062
new_branch.set_bound_location(branch.get_bound_location())
3063
new_branch.set_push_location(branch.get_push_location())
3067
# New branch has no tags by default
3068
new_branch.tags._set_tag_dict({})
3070
# Copying done; now update target format
3071
new_branch._transport.put_bytes('format',
3073
mode=new_branch.bzrdir._get_file_mode())
3075
# Clean up old files
3076
new_branch._transport.delete('revision-history')
3080
branch.set_parent(None)
3081
except errors.NoSuchFile:
3083
branch.set_bound_location(None)
3088
class Converter6to7(object):
3089
"""Perform an in-place upgrade of format 6 to format 7"""
3091
def convert(self, branch):
3092
format = BzrBranchFormat7()
3093
branch._set_config_location('stacked_on_location', '')
3094
# update target format
3095
branch._transport.put_bytes('format', format.as_string())
3098
class Converter7to8(object):
3099
"""Perform an in-place upgrade of format 7 to format 8"""
3101
def convert(self, branch):
3102
format = BzrBranchFormat8()
3103
branch._transport.put_bytes('references', '')
3104
# update target format
3105
branch._transport.put_bytes('format', format.as_string())
3108
class InterBranch(InterObject):
3109
"""This class represents operations taking place between two branches.
3111
Its instances have methods like pull() and push() and contain
3112
references to the source and target repositories these operations
3113
can be carried out on.
3117
"""The available optimised InterBranch types."""
3120
def _get_branch_formats_to_test(klass):
3121
"""Return an iterable of format tuples for testing.
1195
inv = self.read_working_inventory()
1196
if old_tree is None:
1197
old_tree = self.basis_tree()
1198
old_inv = old_tree.inventory
1201
for fn in filenames:
1202
file_id = inv.path2id(fn)
1204
raise NotVersionedError("not a versioned file", fn)
1205
if not old_inv.has_id(file_id):
1206
raise BzrError("file not present in old tree", fn, file_id)
1207
nids.append((fn, file_id))
1209
# TODO: Rename back if it was previously at a different location
1211
# TODO: If given a directory, restore the entire contents from
1212
# the previous version.
1214
# TODO: Make a backup to a temporary file.
1216
# TODO: If the file previously didn't exist, delete it?
1217
for fn, file_id in nids:
1220
f = AtomicFile(fn, 'wb')
1222
f.write(old_tree.get_file(file_id).read())
1228
def pending_merges(self):
1229
"""Return a list of pending merges.
1231
These are revisions that have been merged into the working
1232
directory but not yet committed.
1234
cfn = self.controlfilename('pending-merges')
1235
if not os.path.exists(cfn):
3123
:return: An iterable of (from_format, to_format) to use when testing
3124
this InterBranch class. Each InterBranch class should define this
3127
raise NotImplementedError(klass._get_branch_formats_to_test)
3130
def pull(self, overwrite=False, stop_revision=None,
3131
possible_transports=None, local=False):
3132
"""Mirror source into target branch.
3134
The target branch is considered to be 'local', having low latency.
3136
:returns: PullResult instance
3138
raise NotImplementedError(self.pull)
3141
def push(self, overwrite=False, stop_revision=None, lossy=False,
3142
_override_hook_source_branch=None):
3143
"""Mirror the source branch into the target branch.
3145
The source branch is considered to be 'local', having low latency.
3147
raise NotImplementedError(self.push)
3150
def copy_content_into(self, revision_id=None):
3151
"""Copy the content of source into target
3153
revision_id: if not None, the revision history in the new branch will
3154
be truncated to end with revision_id.
3156
raise NotImplementedError(self.copy_content_into)
3159
def fetch(self, stop_revision=None, limit=None):
3162
:param stop_revision: Last revision to fetch
3163
:param limit: Optional rough limit of revisions to fetch
3165
raise NotImplementedError(self.fetch)
3168
def _fix_overwrite_type(overwrite):
3169
if isinstance(overwrite, bool):
3171
return ["history", "tags"]
1238
for l in self.controlfile('pending-merges', 'r').readlines():
1239
p.append(l.rstrip('\n'))
1243
def add_pending_merge(self, revision_id):
1244
from bzrlib.revision import validate_revision_id
1246
validate_revision_id(revision_id)
1248
p = self.pending_merges()
1249
if revision_id in p:
1251
p.append(revision_id)
1252
self.set_pending_merges(p)
1255
def set_pending_merges(self, rev_list):
1256
from bzrlib.atomicfile import AtomicFile
1259
f = AtomicFile(self.controlfilename('pending-merges'))
3177
class GenericInterBranch(InterBranch):
3178
"""InterBranch implementation that uses public Branch functions."""
3181
def is_compatible(klass, source, target):
3182
# GenericBranch uses the public API, so always compatible
3186
def _get_branch_formats_to_test(klass):
3187
return [(format_registry.get_default(), format_registry.get_default())]
3190
def unwrap_format(klass, format):
3191
if isinstance(format, remote.RemoteBranchFormat):
3192
format._ensure_real()
3193
return format._custom_format
3197
def copy_content_into(self, revision_id=None):
3198
"""Copy the content of source into target
3200
revision_id: if not None, the revision history in the new branch will
3201
be truncated to end with revision_id.
3203
self.source.update_references(self.target)
3204
self.source._synchronize_history(self.target, revision_id)
3206
parent = self.source.get_parent()
3207
except errors.InaccessibleParent, e:
3208
mutter('parent was not accessible to copy: %s', e)
3211
self.target.set_parent(parent)
3212
if self.source._push_should_merge_tags():
3213
self.source.tags.merge_to(self.target.tags)
3216
def fetch(self, stop_revision=None, limit=None):
3217
if self.target.base == self.source.base:
3219
self.source.lock_read()
3221
fetch_spec_factory = fetch.FetchSpecFactory()
3222
fetch_spec_factory.source_branch = self.source
3223
fetch_spec_factory.source_branch_stop_revision_id = stop_revision
3224
fetch_spec_factory.source_repo = self.source.repository
3225
fetch_spec_factory.target_repo = self.target.repository
3226
fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
3227
fetch_spec_factory.limit = limit
3228
fetch_spec = fetch_spec_factory.make_fetch_spec()
3229
return self.target.repository.fetch(self.source.repository,
3230
fetch_spec=fetch_spec)
3232
self.source.unlock()
3235
def _update_revisions(self, stop_revision=None, overwrite=False,
3237
other_revno, other_last_revision = self.source.last_revision_info()
3238
stop_revno = None # unknown
3239
if stop_revision is None:
3240
stop_revision = other_last_revision
3241
if _mod_revision.is_null(stop_revision):
3242
# if there are no commits, we're done.
3244
stop_revno = other_revno
3246
# what's the current last revision, before we fetch [and change it
3248
last_rev = _mod_revision.ensure_null(self.target.last_revision())
3249
# we fetch here so that we don't process data twice in the common
3250
# case of having something to pull, and so that the check for
3251
# already merged can operate on the just fetched graph, which will
3252
# be cached in memory.
3253
self.fetch(stop_revision=stop_revision)
3254
# Check to see if one is an ancestor of the other
3257
graph = self.target.repository.get_graph()
3258
if self.target._check_if_descendant_or_diverged(
3259
stop_revision, last_rev, graph, self.source):
3260
# stop_revision is a descendant of last_rev, but we aren't
3261
# overwriting, so we're done.
3263
if stop_revno is None:
3265
graph = self.target.repository.get_graph()
3266
this_revno, this_last_revision = \
3267
self.target.last_revision_info()
3268
stop_revno = graph.find_distance_to_null(stop_revision,
3269
[(other_last_revision, other_revno),
3270
(this_last_revision, this_revno)])
3271
self.target.set_last_revision_info(stop_revno, stop_revision)
3274
def pull(self, overwrite=False, stop_revision=None,
3275
possible_transports=None, run_hooks=True,
3276
_override_hook_target=None, local=False):
3277
"""Pull from source into self, updating my master if any.
3279
:param run_hooks: Private parameter - if false, this branch
3280
is being called because it's the master of the primary branch,
3281
so it should not run its hooks.
3283
bound_location = self.target.get_bound_location()
3284
if local and not bound_location:
3285
raise errors.LocalRequiresBoundBranch()
3286
master_branch = None
3287
source_is_master = False
3289
# bound_location comes from a config file, some care has to be
3290
# taken to relate it to source.user_url
3291
normalized = urlutils.normalize_url(bound_location)
1271
class ScratchBranch(Branch):
1272
"""Special test class: a branch that cleans up after itself.
1274
>>> b = ScratchBranch()
1282
def __init__(self, files=[], dirs=[], base=None):
1283
"""Make a test branch.
1285
This creates a temporary directory and runs init-tree in it.
1287
If any files are listed, they are created in the working copy.
1289
from tempfile import mkdtemp
1294
Branch.__init__(self, base, init=init)
1296
os.mkdir(self.abspath(d))
1299
file(os.path.join(self.base, f), 'w').write('content of %s' % f)
1304
>>> orig = ScratchBranch(files=["file1", "file2"])
1305
>>> clone = orig.clone()
1306
>>> os.path.samefile(orig.base, clone.base)
1308
>>> os.path.isfile(os.path.join(clone.base, "file1"))
1311
from shutil import copytree
1312
from tempfile import mkdtemp
1315
copytree(self.base, base, symlinks=True)
1316
return ScratchBranch(base=base)
1322
"""Destroy the test branch, removing the scratch directory."""
1323
from shutil import rmtree
1326
mutter("delete ScratchBranch %s" % self.base)
1329
# Work around for shutil.rmtree failing on Windows when
1330
# readonly files are encountered
1331
mutter("hit exception in destroying ScratchBranch: %s" % e)
1332
for root, dirs, files in os.walk(self.base, topdown=False):
1334
os.chmod(os.path.join(root, name), 0700)
1340
######################################################################
1344
def is_control_file(filename):
1345
## FIXME: better check
1346
filename = os.path.normpath(filename)
1347
while filename != '':
1348
head, tail = os.path.split(filename)
1349
## mutter('check %r for control file' % ((head, tail), ))
1350
if tail == bzrlib.BZRDIR:
1352
if filename == head:
1359
def gen_file_id(name):
1360
"""Return new file id.
1362
This should probably generate proper UUIDs, but for the moment we
1363
cope with just randomness because running uuidgen every time is
1366
from binascii import hexlify
1367
from time import time
1369
# get last component
1370
idx = name.rfind('/')
1372
name = name[idx+1 : ]
1373
idx = name.rfind('\\')
1375
name = name[idx+1 : ]
1377
# make it not a hidden file
1378
name = name.lstrip('.')
1380
# remove any wierd characters; we don't escape them but rather
1381
# just pull them out
1382
name = re.sub(r'[^\w.]', '', name)
1384
s = hexlify(rand_bytes(8))
1385
return '-'.join((name, compact_date(time()), s))
1389
"""Return a new tree-root file id."""
1390
return gen_file_id('TREE_ROOT')
3293
relpath = self.source.user_transport.relpath(normalized)
3294
source_is_master = (relpath == '')
3295
except (errors.PathNotChild, errors.InvalidURL):
3296
source_is_master = False
3297
if not local and bound_location and not source_is_master:
3298
# not pulling from master, so we need to update master.
3299
master_branch = self.target.get_master_branch(possible_transports)
3300
master_branch.lock_write()
3303
# pull from source into master.
3304
master_branch.pull(self.source, overwrite, stop_revision,
3306
return self._pull(overwrite,
3307
stop_revision, _hook_master=master_branch,
3308
run_hooks=run_hooks,
3309
_override_hook_target=_override_hook_target,
3310
merge_tags_to_master=not source_is_master)
3313
master_branch.unlock()
3315
def push(self, overwrite=False, stop_revision=None, lossy=False,
3316
_override_hook_source_branch=None):
3317
"""See InterBranch.push.
3319
This is the basic concrete implementation of push()
3321
:param _override_hook_source_branch: If specified, run the hooks
3322
passing this Branch as the source, rather than self. This is for
3323
use of RemoteBranch, where push is delegated to the underlying
3327
raise errors.LossyPushToSameVCS(self.source, self.target)
3328
# TODO: Public option to disable running hooks - should be trivial but
3331
op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
3332
op.add_cleanup(self.source.lock_read().unlock)
3333
op.add_cleanup(self.target.lock_write().unlock)
3334
return op.run(overwrite, stop_revision,
3335
_override_hook_source_branch=_override_hook_source_branch)
3337
def _basic_push(self, overwrite, stop_revision):
3338
"""Basic implementation of push without bound branches or hooks.
3340
Must be called with source read locked and target write locked.
3342
result = BranchPushResult()
3343
result.source_branch = self.source
3344
result.target_branch = self.target
3345
result.old_revno, result.old_revid = self.target.last_revision_info()
3346
self.source.update_references(self.target)
3347
overwrite = _fix_overwrite_type(overwrite)
3348
if result.old_revid != stop_revision:
3349
# We assume that during 'push' this repository is closer than
3351
graph = self.source.repository.get_graph(self.target.repository)
3352
self._update_revisions(stop_revision,
3353
overwrite=("history" in overwrite),
3355
if self.source._push_should_merge_tags():
3356
result.tag_updates, result.tag_conflicts = (
3357
self.source.tags.merge_to(
3358
self.target.tags, "tags" in overwrite))
3359
result.new_revno, result.new_revid = self.target.last_revision_info()
3362
def _push_with_bound_branches(self, operation, overwrite, stop_revision,
3363
_override_hook_source_branch=None):
3364
"""Push from source into target, and into target's master if any.
3367
if _override_hook_source_branch:
3368
result.source_branch = _override_hook_source_branch
3369
for hook in Branch.hooks['post_push']:
3372
bound_location = self.target.get_bound_location()
3373
if bound_location and self.target.base != bound_location:
3374
# there is a master branch.
3376
# XXX: Why the second check? Is it even supported for a branch to
3377
# be bound to itself? -- mbp 20070507
3378
master_branch = self.target.get_master_branch()
3379
master_branch.lock_write()
3380
operation.add_cleanup(master_branch.unlock)
3381
# push into the master from the source branch.
3382
master_inter = InterBranch.get(self.source, master_branch)
3383
master_inter._basic_push(overwrite, stop_revision)
3384
# and push into the target branch from the source. Note that
3385
# we push from the source branch again, because it's considered
3386
# the highest bandwidth repository.
3387
result = self._basic_push(overwrite, stop_revision)
3388
result.master_branch = master_branch
3389
result.local_branch = self.target
3391
master_branch = None
3393
result = self._basic_push(overwrite, stop_revision)
3394
# TODO: Why set master_branch and local_branch if there's no
3395
# binding? Maybe cleaner to just leave them unset? -- mbp
3397
result.master_branch = self.target
3398
result.local_branch = None
3402
def _pull(self, overwrite=False, stop_revision=None,
3403
possible_transports=None, _hook_master=None, run_hooks=True,
3404
_override_hook_target=None, local=False,
3405
merge_tags_to_master=True):
3408
This function is the core worker, used by GenericInterBranch.pull to
3409
avoid duplication when pulling source->master and source->local.
3411
:param _hook_master: Private parameter - set the branch to
3412
be supplied as the master to pull hooks.
3413
:param run_hooks: Private parameter - if false, this branch
3414
is being called because it's the master of the primary branch,
3415
so it should not run its hooks.
3416
is being called because it's the master of the primary branch,
3417
so it should not run its hooks.
3418
:param _override_hook_target: Private parameter - set the branch to be
3419
supplied as the target_branch to pull hooks.
3420
:param local: Only update the local branch, and not the bound branch.
3422
# This type of branch can't be bound.
3424
raise errors.LocalRequiresBoundBranch()
3425
result = PullResult()
3426
result.source_branch = self.source
3427
if _override_hook_target is None:
3428
result.target_branch = self.target
3430
result.target_branch = _override_hook_target
3431
self.source.lock_read()
3433
# We assume that during 'pull' the target repository is closer than
3435
self.source.update_references(self.target)
3436
graph = self.target.repository.get_graph(self.source.repository)
3437
# TODO: Branch formats should have a flag that indicates
3438
# that revno's are expensive, and pull() should honor that flag.
3440
result.old_revno, result.old_revid = \
3441
self.target.last_revision_info()
3442
overwrite = _fix_overwrite_type(overwrite)
3443
self._update_revisions(stop_revision,
3444
overwrite=("history" in overwrite),
3446
# TODO: The old revid should be specified when merging tags,
3447
# so a tags implementation that versions tags can only
3448
# pull in the most recent changes. -- JRV20090506
3449
result.tag_updates, result.tag_conflicts = (
3450
self.source.tags.merge_to(self.target.tags,
3451
"tags" in overwrite,
3452
ignore_master=not merge_tags_to_master))
3453
result.new_revno, result.new_revid = self.target.last_revision_info()
3455
result.master_branch = _hook_master
3456
result.local_branch = result.target_branch
3458
result.master_branch = result.target_branch
3459
result.local_branch = None
3461
for hook in Branch.hooks['post_pull']:
3464
self.source.unlock()
3468
InterBranch.register_optimiser(GenericInterBranch)