1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
1
# Copyright (C) 2005 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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
from cStringIO import StringIO
20
from bzrlib.lazy_import import lazy_import
21
lazy_import(globals(), """
22
from copy import deepcopy
23
from unittest import TestSuite
24
from warnings import warn
20
import sys, os, os.path, random, time, sha, sets, types, re, shutil, tempfile
21
import traceback, socket, fnmatch, difflib, time
22
from binascii import hexlify
30
config as _mod_config,
35
revision as _mod_revision,
42
from bzrlib.config import BranchConfig, TreeConfig
43
from bzrlib.lockable_files import LockableFiles, TransportLock
44
from bzrlib.tag import (
50
from bzrlib.decorators import needs_read_lock, needs_write_lock
51
from bzrlib.errors import (BzrError, BzrCheckError, DivergedBranches,
52
HistoryMissing, InvalidRevisionId,
53
InvalidRevisionNumber, LockError, NoSuchFile,
54
NoSuchRevision, NoWorkingTree, NotVersionedError,
55
NotBranchError, UninitializableFormat,
56
UnlistableStore, UnlistableBranch,
58
from bzrlib.hooks import Hooks
59
from bzrlib.symbol_versioning import (deprecated_function,
63
zero_eight, zero_nine, zero_sixteen,
65
from bzrlib.trace import mutter, note
68
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
69
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
70
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
73
# TODO: Maybe include checks for common corruption of newlines, etc?
75
# TODO: Some operations like log might retrieve the same revisions
76
# repeatedly to calculate deltas. We could perhaps have a weakref
77
# cache in memory to make this faster. In general anything can be
78
# cached in memory between lock and unlock operations. .. nb thats
79
# what the transaction identity map provides
25
from inventory import Inventory
26
from trace import mutter, note
27
from tree import Tree, EmptyTree, RevisionTree
28
from inventory import InventoryEntry, Inventory
29
from osutils import isdir, quotefn, isfile, uuid, sha_file, username, \
30
format_date, compact_date, pumpfile, user_email, rand_bytes, splitpath, \
31
joinpath, sha_string, file_kind, local_time_offset, appendpath
32
from store import ImmutableStore
33
from revision import Revision
34
from errors import bailout, BzrError
35
from textui import show_status
37
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
38
## TODO: Maybe include checks for common corruption of newlines, etc?
42
def find_branch(f, **args):
43
if f and (f.startswith('http://') or f.startswith('https://')):
45
return remotebranch.RemoteBranch(f, **args)
47
return Branch(f, **args)
50
def find_branch_root(f=None):
51
"""Find the branch root enclosing f, or pwd.
53
f may be a filename or a URL.
55
It is not necessary that f exists.
57
Basically we keep looking up until we find the control directory or
61
elif hasattr(os.path, 'realpath'):
62
f = os.path.realpath(f)
64
f = os.path.abspath(f)
65
if not os.path.exists(f):
66
raise BzrError('%r does not exist' % f)
72
if os.path.exists(os.path.join(f, bzrlib.BZRDIR)):
74
head, tail = os.path.split(f)
76
# reached the root, whatever that may be
77
raise BzrError('%r is not in a branch' % orig_f)
82
82
######################################################################
86
86
"""Branch holding a history of revisions.
89
Base directory/url of the branch.
91
hooks: An instance of BranchHooks.
89
Base directory of the branch.
93
# this is really an instance variable - FIXME move it there
97
# override this to set the strategy for storing tags
99
return DisabledTags(self)
101
def __init__(self, *ignored, **ignored_too):
102
self.tags = self._make_tags()
103
self._revision_history_cache = None
104
self._revision_id_to_revno_cache = None
106
def break_lock(self):
107
"""Break a lock if one is present from another instance.
109
Uses the ui factory to ask for confirmation if the lock may be from
112
This will probe the repository for its lock as well.
114
self.control_files.break_lock()
115
self.repository.break_lock()
116
master = self.get_master_branch()
117
if master is not None:
121
@deprecated_method(zero_eight)
122
def open_downlevel(base):
123
"""Open a branch which may be of an old format."""
124
return Branch.open(base, _unsupported=True)
127
def open(base, _unsupported=False):
128
"""Open the branch rooted at base.
130
For instance, if the branch is at URL/.bzr/branch,
131
Branch.open(URL) -> a Branch instance.
133
control = bzrdir.BzrDir.open(base, _unsupported)
134
return control.open_branch(_unsupported)
137
def open_from_transport(transport, _unsupported=False):
138
"""Open the branch rooted at transport"""
139
control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
140
return control.open_branch(_unsupported)
143
def open_containing(url, possible_transports=None):
144
"""Open an existing branch which contains url.
146
This probes for a branch at url, and searches upwards from there.
148
Basically we keep looking up until we find the control directory or
149
run into the root. If there isn't one, raises NotBranchError.
150
If there is one and it is either an unrecognised format or an unsupported
151
format, UnknownFormatError or UnsupportedFormatError are raised.
152
If there is one, it is returned, along with the unused portion of url.
154
control, relpath = bzrdir.BzrDir.open_containing(url,
156
return control.open_branch(), relpath
159
@deprecated_function(zero_eight)
160
def initialize(base):
161
"""Create a new working tree and branch, rooted at 'base' (url)
163
NOTE: This will soon be deprecated in favour of creation
166
return bzrdir.BzrDir.create_standalone_workingtree(base).branch
168
@deprecated_function(zero_eight)
169
def setup_caching(self, cache_root):
170
"""Subclasses that care about caching should override this, and set
171
up cached stores located under cache_root.
173
NOTE: This is unused.
177
def get_config(self):
178
return BranchConfig(self)
181
return self.get_config().get_nickname()
183
def _set_nick(self, nick):
184
self.get_config().set_user_option('nickname', nick)
186
nick = property(_get_nick, _set_nick)
189
raise NotImplementedError(self.is_locked)
191
def lock_write(self):
192
raise NotImplementedError(self.lock_write)
195
raise NotImplementedError(self.lock_read)
198
raise NotImplementedError(self.unlock)
200
def peek_lock_mode(self):
201
"""Return lock mode for the Branch: 'r', 'w' or None"""
202
raise NotImplementedError(self.peek_lock_mode)
204
def get_physical_lock_status(self):
205
raise NotImplementedError(self.get_physical_lock_status)
208
def get_revision_id_to_revno_map(self):
209
"""Return the revision_id => dotted revno map.
211
This will be regenerated on demand, but will be cached.
213
:return: A dictionary mapping revision_id => dotted revno.
214
This dictionary should not be modified by the caller.
216
if self._revision_id_to_revno_cache is not None:
217
mapping = self._revision_id_to_revno_cache
93
def __init__(self, base, init=False, find_root=True, lock_mode='w'):
94
"""Create new branch object at a particular location.
96
base -- Base directory for the branch.
98
init -- If True, create new control files in a previously
99
unversioned directory. If False, the branch must already
102
find_root -- If true and init is false, find the root of the
103
existing branch containing base.
105
In the test suite, creation of new trees is tested using the
106
`ScratchBranch` class.
109
self.base = os.path.realpath(base)
112
self.base = find_branch_root(base)
219
mapping = self._gen_revno_map()
220
self._cache_revision_id_to_revno(mapping)
221
# TODO: jam 20070417 Since this is being cached, should we be returning
223
# I would rather not, and instead just declare that users should not
224
# modify the return value.
227
def _gen_revno_map(self):
228
"""Create a new mapping from revision ids to dotted revnos.
230
Dotted revnos are generated based on the current tip in the revision
232
This is the worker function for get_revision_id_to_revno_map, which
233
just caches the return value.
235
:return: A dictionary mapping revision_id => dotted revno.
237
last_revision = self.last_revision()
238
revision_graph = self.repository.get_revision_graph(last_revision)
239
merge_sorted_revisions = tsort.merge_sort(
244
revision_id_to_revno = dict((rev_id, revno)
245
for seq_num, rev_id, depth, revno, end_of_merge
246
in merge_sorted_revisions)
247
return revision_id_to_revno
249
def leave_lock_in_place(self):
250
"""Tell this branch object not to release the physical lock when this
253
If lock_write doesn't return a token, then this method is not supported.
255
self.control_files.leave_in_place()
257
def dont_leave_lock_in_place(self):
258
"""Tell this branch object to release the physical lock when this
259
object is unlocked, even if it didn't originally acquire it.
261
If lock_write doesn't return a token, then this method is not supported.
263
self.control_files.dont_leave_in_place()
114
self.base = os.path.realpath(base)
115
if not isdir(self.controlfilename('.')):
116
bailout("not a bzr branch: %s" % quotefn(base),
117
['use "bzr init" to initialize a new working tree',
118
'current bzr can only operate from top-of-tree'])
122
self.text_store = ImmutableStore(self.controlfilename('text-store'))
123
self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
124
self.inventory_store = ImmutableStore(self.controlfilename('inventory-store'))
128
return '%s(%r)' % (self.__class__.__name__, self.base)
135
def lock(self, mode='w'):
136
"""Lock the on-disk branch, excluding other processes."""
142
om = os.O_WRONLY | os.O_CREAT
147
raise BzrError("invalid locking mode %r" % mode)
150
lockfile = os.open(self.controlfilename('branch-lock'), om)
152
if e.errno == errno.ENOENT:
153
# might not exist on branches from <0.0.4
154
self.controlfile('branch-lock', 'w').close()
155
lockfile = os.open(self.controlfilename('branch-lock'), om)
159
fcntl.lockf(lockfile, lm)
161
fcntl.lockf(lockfile, fcntl.LOCK_UN)
163
self._lockmode = None
165
self._lockmode = mode
167
warning("please write a locking method for platform %r" % sys.platform)
169
self._lockmode = None
171
self._lockmode = mode
174
def _need_readlock(self):
175
if self._lockmode not in ['r', 'w']:
176
raise BzrError('need read lock on branch, only have %r' % self._lockmode)
178
def _need_writelock(self):
179
if self._lockmode not in ['w']:
180
raise BzrError('need write lock on branch, only have %r' % self._lockmode)
265
183
def abspath(self, name):
266
"""Return absolute filename for something in the branch
268
XXX: Robert Collins 20051017 what is this used for? why is it a branch
269
method and not a tree method.
271
raise NotImplementedError(self.abspath)
273
def bind(self, other):
274
"""Bind the local branch the other branch.
276
:param other: The branch to bind to
279
raise errors.UpgradeRequired(self.base)
282
def fetch(self, from_branch, last_revision=None, pb=None):
283
"""Copy revisions from from_branch into this branch.
285
:param from_branch: Where to copy from.
286
:param last_revision: What revision to stop at (None for at the end
288
:param pb: An optional progress bar to use.
290
Returns the copied revision count and the failed revisions in a tuple:
293
if self.base == from_branch.base:
296
nested_pb = ui.ui_factory.nested_progress_bar()
301
from_branch.lock_read()
303
if last_revision is None:
304
pb.update('get source history')
305
last_revision = from_branch.last_revision()
306
if last_revision is None:
307
last_revision = _mod_revision.NULL_REVISION
308
return self.repository.fetch(from_branch.repository,
309
revision_id=last_revision,
312
if nested_pb is not None:
316
def get_bound_location(self):
317
"""Return the URL of the branch we are bound to.
319
Older format branches cannot bind, please be sure to use a metadir
324
def get_old_bound_location(self):
325
"""Return the URL of the branch we used to be bound to
327
raise errors.UpgradeRequired(self.base)
329
def get_commit_builder(self, parents, config=None, timestamp=None,
330
timezone=None, committer=None, revprops=None,
332
"""Obtain a CommitBuilder for this branch.
334
:param parents: Revision ids of the parents of the new revision.
335
:param config: Optional configuration to use.
336
:param timestamp: Optional timestamp recorded for commit.
337
:param timezone: Optional timezone for timestamp.
338
:param committer: Optional committer to set for commit.
339
:param revprops: Optional dictionary of revision properties.
340
:param revision_id: Optional revision id.
344
config = self.get_config()
346
return self.repository.get_commit_builder(self, parents, config,
347
timestamp, timezone, committer, revprops, revision_id)
349
def get_master_branch(self):
350
"""Return the branch we are bound to.
352
:return: Either a Branch, or None
356
def get_revision_delta(self, revno):
357
"""Return the delta for one revision.
359
The delta is relative to its mainline predecessor, or the
360
empty tree for revision 1.
362
assert isinstance(revno, int)
363
rh = self.revision_history()
364
if not (1 <= revno <= len(rh)):
365
raise InvalidRevisionNumber(revno)
366
return self.repository.get_revision_delta(rh[revno-1])
368
@deprecated_method(zero_sixteen)
369
def get_root_id(self):
370
"""Return the id of this branches root
372
Deprecated: branches don't have root ids-- trees do.
373
Use basis_tree().get_root_id() instead.
375
raise NotImplementedError(self.get_root_id)
377
def print_file(self, file, revision_id):
184
"""Return absolute filename for something in the branch"""
185
return os.path.join(self.base, name)
188
def relpath(self, path):
189
"""Return path relative to this branch of something inside it.
191
Raises an error if path is not in this branch."""
192
rp = os.path.realpath(path)
194
if not rp.startswith(self.base):
195
bailout("path %r is not within branch %r" % (rp, self.base))
196
rp = rp[len(self.base):]
197
rp = rp.lstrip(os.sep)
201
def controlfilename(self, file_or_path):
202
"""Return location relative to branch."""
203
if isinstance(file_or_path, types.StringTypes):
204
file_or_path = [file_or_path]
205
return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
208
def controlfile(self, file_or_path, mode='r'):
209
"""Open a control file for this branch.
211
There are two classes of file in the control directory: text
212
and binary. binary files are untranslated byte streams. Text
213
control files are stored with Unix newlines and in UTF-8, even
214
if the platform or locale defaults are different.
216
Controlfiles should almost never be opened in write mode but
217
rather should be atomically copied and replaced using atomicfile.
220
fn = self.controlfilename(file_or_path)
222
if mode == 'rb' or mode == 'wb':
223
return file(fn, mode)
224
elif mode == 'r' or mode == 'w':
225
# open in binary mode anyhow so there's no newline translation;
226
# codecs uses line buffering by default; don't want that.
228
return codecs.open(fn, mode + 'b', 'utf-8',
231
raise BzrError("invalid controlfile mode %r" % mode)
235
def _make_control(self):
236
os.mkdir(self.controlfilename([]))
237
self.controlfile('README', 'w').write(
238
"This is a Bazaar-NG control directory.\n"
239
"Do not change any files in this directory.")
240
self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT)
241
for d in ('text-store', 'inventory-store', 'revision-store'):
242
os.mkdir(self.controlfilename(d))
243
for f in ('revision-history', 'merged-patches',
244
'pending-merged-patches', 'branch-name',
246
self.controlfile(f, 'w').write('')
247
mutter('created control directory in ' + self.base)
248
Inventory().write_xml(self.controlfile('inventory','w'))
251
def _check_format(self):
252
"""Check this branch format is supported.
254
The current tool only supports the current unstable format.
256
In the future, we might need different in-memory Branch
257
classes to support downlevel branches. But not yet.
259
# This ignores newlines so that we can open branches created
260
# on Windows from Linux and so on. I think it might be better
261
# to always make all internal files in unix format.
262
fmt = self.controlfile('branch-format', 'r').read()
263
fmt.replace('\r\n', '')
264
if fmt != BZR_BRANCH_FORMAT:
265
bailout('sorry, branch format %r not supported' % fmt,
266
['use a different bzr version',
267
'or remove the .bzr directory and "bzr init" again'])
270
def read_working_inventory(self):
271
"""Read the working inventory."""
272
self._need_readlock()
274
# ElementTree does its own conversion from UTF-8, so open in
276
inv = Inventory.read_xml(self.controlfile('inventory', 'rb'))
277
mutter("loaded inventory of %d items in %f"
278
% (len(inv), time.time() - before))
282
def _write_inventory(self, inv):
283
"""Update the working inventory.
285
That is to say, the inventory describing changes underway, that
286
will be committed to the next revision.
288
self._need_writelock()
289
## TODO: factor out to atomicfile? is rename safe on windows?
290
## TODO: Maybe some kind of clean/dirty marker on inventory?
291
tmpfname = self.controlfilename('inventory.tmp')
292
tmpf = file(tmpfname, 'wb')
295
inv_fname = self.controlfilename('inventory')
296
if sys.platform == 'win32':
298
os.rename(tmpfname, inv_fname)
299
mutter('wrote working inventory')
302
inventory = property(read_working_inventory, _write_inventory, None,
303
"""Inventory for the working copy.""")
306
def add(self, files, verbose=False, ids=None):
307
"""Make files versioned.
309
Note that the command line normally calls smart_add instead.
311
This puts the files in the Added state, so that they will be
312
recorded by the next commit.
314
TODO: Perhaps have an option to add the ids even if the files do
317
TODO: Perhaps return the ids of the files? But then again it
318
is easy to retrieve them if they're needed.
320
TODO: Option to specify file id.
322
TODO: Adding a directory should optionally recurse down and
323
add all non-ignored children. Perhaps do that in a
326
self._need_writelock()
328
# TODO: Re-adding a file that is removed in the working copy
329
# should probably put it back with the previous ID.
330
if isinstance(files, types.StringTypes):
331
assert(ids is None or isinstance(ids, types.StringTypes))
337
ids = [None] * len(files)
339
assert(len(ids) == len(files))
341
inv = self.read_working_inventory()
342
for f,file_id in zip(files, ids):
343
if is_control_file(f):
344
bailout("cannot add control file %s" % quotefn(f))
349
bailout("cannot add top-level %r" % f)
351
fullpath = os.path.normpath(self.abspath(f))
354
kind = file_kind(fullpath)
356
# maybe something better?
357
bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
359
if kind != 'file' and kind != 'directory':
360
bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
363
file_id = gen_file_id(f)
364
inv.add_path(f, kind=kind, file_id=file_id)
367
show_status('A', kind, quotefn(f))
369
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
371
self._write_inventory(inv)
374
def print_file(self, file, revno):
378
375
"""Print `file` to stdout."""
379
raise NotImplementedError(self.print_file)
381
def append_revision(self, *revision_ids):
382
raise NotImplementedError(self.append_revision)
384
def set_revision_history(self, rev_history):
385
raise NotImplementedError(self.set_revision_history)
387
def _cache_revision_history(self, rev_history):
388
"""Set the cached revision history to rev_history.
390
The revision_history method will use this cache to avoid regenerating
391
the revision history.
393
This API is semi-public; it only for use by subclasses, all other code
394
should consider it to be private.
396
self._revision_history_cache = rev_history
398
def _cache_revision_id_to_revno(self, revision_id_to_revno):
399
"""Set the cached revision_id => revno map to revision_id_to_revno.
401
This API is semi-public; it only for use by subclasses, all other code
402
should consider it to be private.
404
self._revision_id_to_revno_cache = revision_id_to_revno
406
def _clear_cached_state(self):
407
"""Clear any cached data on this branch, e.g. cached revision history.
409
This means the next call to revision_history will need to call
410
_gen_revision_history.
412
This API is semi-public; it only for use by subclasses, all other code
413
should consider it to be private.
415
self._revision_history_cache = None
416
self._revision_id_to_revno_cache = None
418
def _gen_revision_history(self):
419
"""Return sequence of revision hashes on to this branch.
421
Unlike revision_history, this method always regenerates or rereads the
422
revision history, i.e. it does not cache the result, so repeated calls
425
Concrete subclasses should override this instead of revision_history so
426
that subclasses do not need to deal with caching logic.
428
This API is semi-public; it only for use by subclasses, all other code
429
should consider it to be private.
431
raise NotImplementedError(self._gen_revision_history)
376
self._need_readlock()
377
tree = self.revision_tree(self.lookup_revision(revno))
378
# use inventory as it was in that revision
379
file_id = tree.inventory.path2id(file)
381
bailout("%r is not present in revision %d" % (file, revno))
382
tree.print_file(file_id)
385
def remove(self, files, verbose=False):
386
"""Mark nominated files for removal from the inventory.
388
This does not remove their text. This does not run on
390
TODO: Refuse to remove modified files unless --force is given?
392
TODO: Do something useful with directories.
394
TODO: Should this remove the text or not? Tough call; not
395
removing may be useful and the user can just use use rm, and
396
is the opposite of add. Removing it is consistent with most
397
other tools. Maybe an option.
399
## TODO: Normalize names
400
## TODO: Remove nested loops; better scalability
401
self._need_writelock()
403
if isinstance(files, types.StringTypes):
406
tree = self.working_tree()
409
# do this before any modifications
413
bailout("cannot remove unversioned file %s" % quotefn(f))
414
mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
416
# having remove it, it must be either ignored or unknown
417
if tree.is_ignored(f):
421
show_status(new_status, inv[fid].kind, quotefn(f))
424
self._write_inventory(inv)
426
def set_inventory(self, new_inventory_list):
428
for path, file_id, parent, kind in new_inventory_list:
429
name = os.path.basename(path)
432
inv.add(InventoryEntry(file_id, name, kind, parent))
433
self._write_inventory(inv)
437
"""Return all unknown files.
439
These are files in the working directory that are not versioned or
440
control files or ignored.
442
>>> b = ScratchBranch(files=['foo', 'foo~'])
443
>>> list(b.unknowns())
446
>>> list(b.unknowns())
449
>>> list(b.unknowns())
452
return self.working_tree().unknowns()
455
def append_revision(self, revision_id):
456
mutter("add {%s} to revision-history" % revision_id)
457
rev_history = self.revision_history()
459
tmprhname = self.controlfilename('revision-history.tmp')
460
rhname = self.controlfilename('revision-history')
462
f = file(tmprhname, 'wt')
463
rev_history.append(revision_id)
464
f.write('\n'.join(rev_history))
468
if sys.platform == 'win32':
470
os.rename(tmprhname, rhname)
474
def get_revision(self, revision_id):
475
"""Return the Revision object for a named revision"""
476
self._need_readlock()
477
r = Revision.read_xml(self.revision_store[revision_id])
478
assert r.revision_id == revision_id
482
def get_inventory(self, inventory_id):
483
"""Get Inventory object by hash.
485
TODO: Perhaps for this and similar methods, take a revision
486
parameter which can be either an integer revno or a
488
self._need_readlock()
489
i = Inventory.read_xml(self.inventory_store[inventory_id])
493
def get_revision_inventory(self, revision_id):
494
"""Return inventory of a past revision."""
495
self._need_readlock()
496
if revision_id == None:
499
return self.get_inventory(self.get_revision(revision_id).inventory_id)
434
502
def revision_history(self):
435
503
"""Return sequence of revision hashes on to this branch.
437
This method will cache the revision history for as long as it is safe to
440
if self._revision_history_cache is not None:
441
history = self._revision_history_cache
505
>>> ScratchBranch().revision_history()
508
self._need_readlock()
509
return [l.rstrip('\r\n') for l in self.controlfile('revision-history', 'r').readlines()]
512
def enum_history(self, direction):
513
"""Return (revno, revision_id) for history of branch.
516
'forward' is from earliest to latest
517
'reverse' is from latest to earliest
519
rh = self.revision_history()
520
if direction == 'forward':
525
elif direction == 'reverse':
443
history = self._gen_revision_history()
444
self._cache_revision_history(history)
531
raise BzrError('invalid history direction %r' % direction)
448
535
"""Return current revision number for this branch.
571
660
Note that to_name is only the last component of the new name;
572
661
this doesn't change the directory.
574
This returns a list of (from_path, to_path) pairs for each
577
raise NotImplementedError(self.move)
579
def get_parent(self):
580
"""Return the parent location of the branch.
582
This is the default location for push/pull/missing. The usual
583
pattern is that the user can override it by specifying a
586
raise NotImplementedError(self.get_parent)
588
def _set_config_location(self, name, url, config=None,
589
make_relative=False):
591
config = self.get_config()
595
url = urlutils.relative_url(self.base, url)
596
config.set_user_option(name, url)
598
def _get_config_location(self, name, config=None):
600
config = self.get_config()
601
location = config.get_user_option(name)
606
def get_submit_branch(self):
607
"""Return the submit location of the branch.
609
This is the default location for bundle. The usual
610
pattern is that the user can override it by specifying a
613
return self.get_config().get_user_option('submit_branch')
615
def set_submit_branch(self, location):
616
"""Return the submit location of the branch.
618
This is the default location for bundle. The usual
619
pattern is that the user can override it by specifying a
622
self.get_config().set_user_option('submit_branch', location)
624
def get_public_branch(self):
625
"""Return the public location of the branch.
627
This is is used by merge directives.
629
return self._get_config_location('public_branch')
631
def set_public_branch(self, location):
632
"""Return the submit location of the branch.
634
This is the default location for bundle. The usual
635
pattern is that the user can override it by specifying a
638
self._set_config_location('public_branch', location)
640
def get_push_location(self):
641
"""Return the None or the location to push this branch to."""
642
push_loc = self.get_config().get_user_option('push_location')
645
def set_push_location(self, location):
646
"""Set a new push location for this branch."""
647
raise NotImplementedError(self.set_push_location)
649
def set_parent(self, url):
650
raise NotImplementedError(self.set_parent)
654
"""Synchronise this branch with the master branch if any.
656
:return: None or the last_revision pivoted out during the update.
660
def check_revno(self, revno):
662
Check whether a revno corresponds to any revision.
663
Zero (the NULL revision) is considered valid.
666
self.check_real_revno(revno)
663
self._need_writelock()
664
## TODO: Option to move IDs only
665
assert not isinstance(from_paths, basestring)
666
tree = self.working_tree()
668
to_abs = self.abspath(to_name)
669
if not isdir(to_abs):
670
bailout("destination %r is not a directory" % to_abs)
671
if not tree.has_filename(to_name):
672
bailout("destination %r not in working directory" % to_abs)
673
to_dir_id = inv.path2id(to_name)
674
if to_dir_id == None and to_name != '':
675
bailout("destination %r is not a versioned directory" % to_name)
676
to_dir_ie = inv[to_dir_id]
677
if to_dir_ie.kind not in ('directory', 'root_directory'):
678
bailout("destination %r is not a directory" % to_abs)
680
to_idpath = Set(inv.get_idpath(to_dir_id))
683
if not tree.has_filename(f):
684
bailout("%r does not exist in working tree" % f)
685
f_id = inv.path2id(f)
687
bailout("%r is not versioned" % f)
688
name_tail = splitpath(f)[-1]
689
dest_path = appendpath(to_name, name_tail)
690
if tree.has_filename(dest_path):
691
bailout("destination %r already exists" % dest_path)
692
if f_id in to_idpath:
693
bailout("can't move %r to a subdirectory of itself" % f)
695
# OK, so there's a race here, it's possible that someone will
696
# create a file in this interval and then the rename might be
697
# left half-done. But we should have caught most problems.
700
name_tail = splitpath(f)[-1]
701
dest_path = appendpath(to_name, name_tail)
702
print "%s => %s" % (f, dest_path)
703
inv.rename(inv.path2id(f), to_dir_id, name_tail)
705
os.rename(self.abspath(f), self.abspath(dest_path))
707
bailout("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
708
["rename rolled back"])
710
self._write_inventory(inv)
715
class ScratchBranch(Branch):
716
"""Special test class: a branch that cleans up after itself.
718
>>> b = ScratchBranch()
726
def __init__(self, files=[], dirs=[]):
727
"""Make a test branch.
729
This creates a temporary directory and runs init-tree in it.
731
If any files are listed, they are created in the working copy.
733
Branch.__init__(self, tempfile.mkdtemp(), init=True)
735
os.mkdir(self.abspath(d))
668
def check_real_revno(self, revno):
670
Check whether a revno corresponds to a real revision.
671
Zero (the NULL revision) is considered invalid
673
if revno < 1 or revno > self.revno():
674
raise InvalidRevisionNumber(revno)
677
def clone(self, to_bzrdir, revision_id=None):
678
"""Clone this branch into to_bzrdir preserving all semantic values.
680
revision_id: if not None, the revision history in the new branch will
681
be truncated to end with revision_id.
683
result = self._format.initialize(to_bzrdir)
684
self.copy_content_into(result, revision_id=revision_id)
688
def sprout(self, to_bzrdir, revision_id=None):
689
"""Create a new line of development from the branch, into to_bzrdir.
691
revision_id: if not None, the revision history in the new branch will
692
be truncated to end with revision_id.
694
result = self._format.initialize(to_bzrdir)
695
self.copy_content_into(result, revision_id=revision_id)
696
result.set_parent(self.bzrdir.root_transport.base)
699
def _synchronize_history(self, destination, revision_id):
700
"""Synchronize last revision and revision history between branches.
702
This version is most efficient when the destination is also a
703
BzrBranch5, but works for BzrBranch6 as long as the revision
704
history is the true lefthand parent history, and all of the revisions
705
are in the destination's repository. If not, set_revision_history
708
:param destination: The branch to copy the history into
709
:param revision_id: The revision-id to truncate history at. May
710
be None to copy complete history.
712
new_history = self.revision_history()
713
if revision_id is not None:
714
revision_id = osutils.safe_revision_id(revision_id)
716
new_history = new_history[:new_history.index(revision_id) + 1]
718
rev = self.repository.get_revision(revision_id)
719
new_history = rev.get_history(self.repository)[1:]
720
destination.set_revision_history(new_history)
723
def copy_content_into(self, destination, revision_id=None):
724
"""Copy the content of self into destination.
726
revision_id: if not None, the revision history in the new branch will
727
be truncated to end with revision_id.
729
self._synchronize_history(destination, revision_id)
731
parent = self.get_parent()
732
except errors.InaccessibleParent, e:
733
mutter('parent was not accessible to copy: %s', e)
736
destination.set_parent(parent)
737
self.tags.merge_to(destination.tags)
741
"""Check consistency of the branch.
743
In particular this checks that revisions given in the revision-history
744
do actually match up in the revision graph, and that they're all
745
present in the repository.
747
Callers will typically also want to check the repository.
749
:return: A BranchCheckResult.
751
mainline_parent_id = None
752
for revision_id in self.revision_history():
754
revision = self.repository.get_revision(revision_id)
755
except errors.NoSuchRevision, e:
756
raise errors.BzrCheckError("mainline revision {%s} not in repository"
758
# In general the first entry on the revision history has no parents.
759
# But it's not illegal for it to have parents listed; this can happen
760
# in imports from Arch when the parents weren't reachable.
761
if mainline_parent_id is not None:
762
if mainline_parent_id not in revision.parent_ids:
763
raise errors.BzrCheckError("previous revision {%s} not listed among "
765
% (mainline_parent_id, revision_id))
766
mainline_parent_id = revision_id
767
return BranchCheckResult(self)
769
def _get_checkout_format(self):
770
"""Return the most suitable metadir for a checkout of this branch.
771
Weaves are used if this branch's repository uses weaves.
773
if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
774
from bzrlib.repofmt import weaverepo
775
format = bzrdir.BzrDirMetaFormat1()
776
format.repository_format = weaverepo.RepositoryFormat7()
778
format = self.repository.bzrdir.checkout_metadir()
779
format.set_branch_format(self._format)
782
def create_checkout(self, to_location, revision_id=None,
784
"""Create a checkout of a branch.
786
:param to_location: The url to produce the checkout at
787
:param revision_id: The revision to check out
788
:param lightweight: If True, produce a lightweight checkout, otherwise,
789
produce a bound branch (heavyweight checkout)
790
:return: The tree of the created checkout
792
t = transport.get_transport(to_location)
795
format = self._get_checkout_format()
796
checkout = format.initialize_on_transport(t)
797
BranchReferenceFormat().initialize(checkout, self)
799
format = self._get_checkout_format()
800
checkout_branch = bzrdir.BzrDir.create_branch_convenience(
801
to_location, force_new_tree=False, format=format)
802
checkout = checkout_branch.bzrdir
803
checkout_branch.bind(self)
804
# pull up to the specified revision_id to set the initial
805
# branch tip correctly, and seed it with history.
806
checkout_branch.pull(self, stop_revision=revision_id)
807
tree = checkout.create_workingtree(revision_id)
808
basis_tree = tree.basis_tree()
809
basis_tree.lock_read()
811
for path, file_id in basis_tree.iter_references():
812
reference_parent = self.reference_parent(file_id, path)
813
reference_parent.create_checkout(tree.abspath(path),
814
basis_tree.get_reference_revision(file_id, path),
820
def reference_parent(self, file_id, path):
821
"""Return the parent branch for a tree-reference file_id
822
:param file_id: The file_id of the tree reference
823
:param path: The path of the file_id in the tree
824
:return: A branch associated with the file_id
826
# FIXME should provide multiple branches, based on config
827
return Branch.open(self.bzrdir.root_transport.clone(path).base)
829
def supports_tags(self):
830
return self._format.supports_tags()
833
class BranchFormat(object):
834
"""An encapsulation of the initialization and open routines for a format.
836
Formats provide three things:
837
* An initialization routine,
841
Formats are placed in an dict by their format string for reference
842
during branch opening. Its not required that these be instances, they
843
can be classes themselves with class methods - it simply depends on
844
whether state is needed for a given format or not.
846
Once a format is deprecated, just deprecate the initialize and open
847
methods on the format class. Do not deprecate the object, as the
848
object will be created every time regardless.
851
_default_format = None
852
"""The default format used for new branches."""
855
"""The known formats."""
857
def __eq__(self, other):
858
return self.__class__ is other.__class__
860
def __ne__(self, other):
861
return not (self == other)
864
def find_format(klass, a_bzrdir):
865
"""Return the format for the branch object in a_bzrdir."""
867
transport = a_bzrdir.get_branch_transport(None)
868
format_string = transport.get("format").read()
869
return klass._formats[format_string]
871
raise NotBranchError(path=transport.base)
873
raise errors.UnknownFormatError(format=format_string)
876
def get_default_format(klass):
877
"""Return the current default format."""
878
return klass._default_format
880
def get_reference(self, a_bzrdir):
881
"""Get the target reference of the branch in a_bzrdir.
883
format probing must have been completed before calling
884
this method - it is assumed that the format of the branch
885
in a_bzrdir is correct.
887
:param a_bzrdir: The bzrdir to get the branch data from.
888
:return: None if the branch is not a reference branch.
892
def get_format_string(self):
893
"""Return the ASCII format string that identifies this format."""
894
raise NotImplementedError(self.get_format_string)
896
def get_format_description(self):
897
"""Return the short format description for this format."""
898
raise NotImplementedError(self.get_format_description)
900
def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
902
"""Initialize a branch in a bzrdir, with specified files
904
:param a_bzrdir: The bzrdir to initialize the branch in
905
:param utf8_files: The files to create as a list of
906
(filename, content) tuples
907
:param set_format: If True, set the format with
908
self.get_format_string. (BzrBranch4 has its format set
910
:return: a branch in this format
912
mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
913
branch_transport = a_bzrdir.get_branch_transport(self)
915
'metadir': ('lock', lockdir.LockDir),
916
'branch4': ('branch-lock', lockable_files.TransportLock),
918
lock_name, lock_class = lock_map[lock_type]
919
control_files = lockable_files.LockableFiles(branch_transport,
920
lock_name, lock_class)
921
control_files.create_lock()
922
control_files.lock_write()
924
control_files.put_utf8('format', self.get_format_string())
926
for file, content in utf8_files:
927
control_files.put_utf8(file, content)
929
control_files.unlock()
930
return self.open(a_bzrdir, _found=True)
932
def initialize(self, a_bzrdir):
933
"""Create a branch of this format in a_bzrdir."""
934
raise NotImplementedError(self.initialize)
936
def is_supported(self):
937
"""Is this format supported?
939
Supported formats can be initialized and opened.
940
Unsupported formats may not support initialization or committing or
941
some other features depending on the reason for not being supported.
945
def open(self, a_bzrdir, _found=False):
946
"""Return the branch object for a_bzrdir
948
_found is a private parameter, do not use it. It is used to indicate
949
if format probing has already be done.
951
raise NotImplementedError(self.open)
954
def register_format(klass, format):
955
klass._formats[format.get_format_string()] = format
958
def set_default_format(klass, format):
959
klass._default_format = format
962
def unregister_format(klass, format):
963
assert klass._formats[format.get_format_string()] is format
964
del klass._formats[format.get_format_string()]
967
return self.get_format_string().rstrip()
969
def supports_tags(self):
970
"""True if this format supports tags stored in the branch"""
971
return False # by default
973
# XXX: Probably doesn't really belong here -- mbp 20070212
974
def _initialize_control_files(self, a_bzrdir, utf8_files, lock_filename,
976
branch_transport = a_bzrdir.get_branch_transport(self)
977
control_files = lockable_files.LockableFiles(branch_transport,
978
lock_filename, lock_class)
979
control_files.create_lock()
980
control_files.lock_write()
982
for filename, content in utf8_files:
983
control_files.put_utf8(filename, content)
985
control_files.unlock()
988
class BranchHooks(Hooks):
989
"""A dictionary mapping hook name to a list of callables for branch hooks.
991
e.g. ['set_rh'] Is the list of items to be called when the
992
set_revision_history function is invoked.
996
"""Create the default hooks.
998
These are all empty initially, because by default nothing should get
1001
Hooks.__init__(self)
1002
# Introduced in 0.15:
1003
# invoked whenever the revision history has been set
1004
# with set_revision_history. The api signature is
1005
# (branch, revision_history), and the branch will
1008
# invoked after a push operation completes.
1009
# the api signature is
1011
# containing the members
1012
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1013
# where local is the local target branch or None, master is the target
1014
# master branch, and the rest should be self explanatory. The source
1015
# is read locked and the target branches write locked. Source will
1016
# be the local low-latency branch.
1017
self['post_push'] = []
1018
# invoked after a pull operation completes.
1019
# the api signature is
1021
# containing the members
1022
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1023
# where local is the local branch or None, master is the target
1024
# master branch, and the rest should be self explanatory. The source
1025
# is read locked and the target branches write locked. The local
1026
# branch is the low-latency branch.
1027
self['post_pull'] = []
1028
# invoked after a commit operation completes.
1029
# the api signature is
1030
# (local, master, old_revno, old_revid, new_revno, new_revid)
1031
# old_revid is NULL_REVISION for the first commit to a branch.
1032
self['post_commit'] = []
1033
# invoked after a uncommit operation completes.
1034
# the api signature is
1035
# (local, master, old_revno, old_revid, new_revno, new_revid) where
1036
# local is the local branch or None, master is the target branch,
1037
# and an empty branch recieves new_revno of 0, new_revid of None.
1038
self['post_uncommit'] = []
1041
# install the default hooks into the Branch class.
1042
Branch.hooks = BranchHooks()
1045
class BzrBranchFormat4(BranchFormat):
1046
"""Bzr branch format 4.
1049
- a revision-history file.
1050
- a branch-lock lock file [ to be shared with the bzrdir ]
1053
def get_format_description(self):
1054
"""See BranchFormat.get_format_description()."""
1055
return "Branch format 4"
1057
def initialize(self, a_bzrdir):
1058
"""Create a branch of this format in a_bzrdir."""
1059
utf8_files = [('revision-history', ''),
1060
('branch-name', ''),
1062
return self._initialize_helper(a_bzrdir, utf8_files,
1063
lock_type='branch4', set_format=False)
1066
super(BzrBranchFormat4, self).__init__()
1067
self._matchingbzrdir = bzrdir.BzrDirFormat6()
1069
def open(self, a_bzrdir, _found=False):
1070
"""Return the branch object for a_bzrdir
1072
_found is a private parameter, do not use it. It is used to indicate
1073
if format probing has already be done.
1076
# we are being called directly and must probe.
1077
raise NotImplementedError
1078
return BzrBranch(_format=self,
1079
_control_files=a_bzrdir._control_files,
1081
_repository=a_bzrdir.open_repository())
1084
return "Bazaar-NG branch format 4"
1087
class BzrBranchFormat5(BranchFormat):
1088
"""Bzr branch format 5.
1091
- a revision-history file.
1093
- a lock dir guarding the branch itself
1094
- all of this stored in a branch/ subdirectory
1095
- works with shared repositories.
1097
This format is new in bzr 0.8.
1100
def get_format_string(self):
1101
"""See BranchFormat.get_format_string()."""
1102
return "Bazaar-NG branch format 5\n"
1104
def get_format_description(self):
1105
"""See BranchFormat.get_format_description()."""
1106
return "Branch format 5"
1108
def initialize(self, a_bzrdir):
1109
"""Create a branch of this format in a_bzrdir."""
1110
utf8_files = [('revision-history', ''),
1111
('branch-name', ''),
1113
return self._initialize_helper(a_bzrdir, utf8_files)
1116
super(BzrBranchFormat5, self).__init__()
1117
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1119
def open(self, a_bzrdir, _found=False):
1120
"""Return the branch object for a_bzrdir
1122
_found is a private parameter, do not use it. It is used to indicate
1123
if format probing has already be done.
1126
format = BranchFormat.find_format(a_bzrdir)
1127
assert format.__class__ == self.__class__
1129
transport = a_bzrdir.get_branch_transport(None)
1130
control_files = lockable_files.LockableFiles(transport, 'lock',
1132
return BzrBranch5(_format=self,
1133
_control_files=control_files,
1135
_repository=a_bzrdir.find_repository())
1137
raise NotBranchError(path=transport.base)
1140
class BzrBranchFormat6(BzrBranchFormat5):
1141
"""Branch format with last-revision
1143
Unlike previous formats, this has no explicit revision history. Instead,
1144
this just stores the last-revision, and the left-hand history leading
1145
up to there is the history.
1147
This format was introduced in bzr 0.15
1150
def get_format_string(self):
1151
"""See BranchFormat.get_format_string()."""
1152
return "Bazaar Branch Format 6 (bzr 0.15)\n"
1154
def get_format_description(self):
1155
"""See BranchFormat.get_format_description()."""
1156
return "Branch format 6"
1158
def initialize(self, a_bzrdir):
1159
"""Create a branch of this format in a_bzrdir."""
1160
utf8_files = [('last-revision', '0 null:\n'),
1161
('branch-name', ''),
1162
('branch.conf', ''),
1165
return self._initialize_helper(a_bzrdir, utf8_files)
1167
def open(self, a_bzrdir, _found=False):
1168
"""Return the branch object for a_bzrdir
1170
_found is a private parameter, do not use it. It is used to indicate
1171
if format probing has already be done.
1174
format = BranchFormat.find_format(a_bzrdir)
1175
assert format.__class__ == self.__class__
1176
transport = a_bzrdir.get_branch_transport(None)
1177
control_files = lockable_files.LockableFiles(transport, 'lock',
1179
return BzrBranch6(_format=self,
1180
_control_files=control_files,
1182
_repository=a_bzrdir.find_repository())
1184
def supports_tags(self):
1188
class BranchReferenceFormat(BranchFormat):
1189
"""Bzr branch reference format.
1191
Branch references are used in implementing checkouts, they
1192
act as an alias to the real branch which is at some other url.
1199
def get_format_string(self):
1200
"""See BranchFormat.get_format_string()."""
1201
return "Bazaar-NG Branch Reference Format 1\n"
1203
def get_format_description(self):
1204
"""See BranchFormat.get_format_description()."""
1205
return "Checkout reference format 1"
1207
def get_reference(self, a_bzrdir):
1208
"""See BranchFormat.get_reference()."""
1209
transport = a_bzrdir.get_branch_transport(None)
1210
return transport.get('location').read()
1212
def initialize(self, a_bzrdir, target_branch=None):
1213
"""Create a branch of this format in a_bzrdir."""
1214
if target_branch is None:
1215
# this format does not implement branch itself, thus the implicit
1216
# creation contract must see it as uninitializable
1217
raise errors.UninitializableFormat(self)
1218
mutter('creating branch reference in %s', a_bzrdir.transport.base)
1219
branch_transport = a_bzrdir.get_branch_transport(self)
1220
branch_transport.put_bytes('location',
1221
target_branch.bzrdir.root_transport.base)
1222
branch_transport.put_bytes('format', self.get_format_string())
1223
return self.open(a_bzrdir, _found=True)
1226
super(BranchReferenceFormat, self).__init__()
1227
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1229
def _make_reference_clone_function(format, a_branch):
1230
"""Create a clone() routine for a branch dynamically."""
1231
def clone(to_bzrdir, revision_id=None):
1232
"""See Branch.clone()."""
1233
return format.initialize(to_bzrdir, a_branch)
1234
# cannot obey revision_id limits when cloning a reference ...
1235
# FIXME RBC 20060210 either nuke revision_id for clone, or
1236
# emit some sort of warning/error to the caller ?!
1239
def open(self, a_bzrdir, _found=False, location=None):
1240
"""Return the branch that the branch reference in a_bzrdir points at.
1242
_found is a private parameter, do not use it. It is used to indicate
1243
if format probing has already be done.
1246
format = BranchFormat.find_format(a_bzrdir)
1247
assert format.__class__ == self.__class__
1248
if location is None:
1249
location = self.get_reference(a_bzrdir)
1250
real_bzrdir = bzrdir.BzrDir.open(location)
1251
result = real_bzrdir.open_branch()
1252
# this changes the behaviour of result.clone to create a new reference
1253
# rather than a copy of the content of the branch.
1254
# I did not use a proxy object because that needs much more extensive
1255
# testing, and we are only changing one behaviour at the moment.
1256
# If we decide to alter more behaviours - i.e. the implicit nickname
1257
# then this should be refactored to introduce a tested proxy branch
1258
# and a subclass of that for use in overriding clone() and ....
1260
result.clone = self._make_reference_clone_function(result)
1264
# formats which have no format string are not discoverable
1265
# and not independently creatable, so are not registered.
1266
__default_format = BzrBranchFormat5()
1267
BranchFormat.register_format(__default_format)
1268
BranchFormat.register_format(BranchReferenceFormat())
1269
BranchFormat.register_format(BzrBranchFormat6())
1270
BranchFormat.set_default_format(__default_format)
1271
_legacy_formats = [BzrBranchFormat4(),
1274
class BzrBranch(Branch):
1275
"""A branch stored in the actual filesystem.
1277
Note that it's "local" in the context of the filesystem; it doesn't
1278
really matter if it's on an nfs/smb/afs/coda/... share, as long as
1279
it's writable, and can be accessed via the normal filesystem API.
1282
def __init__(self, _format=None,
1283
_control_files=None, a_bzrdir=None, _repository=None):
1284
"""Create new branch object at a particular location."""
1285
Branch.__init__(self)
1286
if a_bzrdir is None:
1287
raise ValueError('a_bzrdir must be supplied')
1289
self.bzrdir = a_bzrdir
1290
# self._transport used to point to the directory containing the
1291
# control directory, but was not used - now it's just the transport
1292
# for the branch control files. mbp 20070212
1293
self._base = self.bzrdir.transport.clone('..').base
1294
self._format = _format
1295
if _control_files is None:
1296
raise ValueError('BzrBranch _control_files is None')
1297
self.control_files = _control_files
1298
self._transport = _control_files._transport
1299
self.repository = _repository
1302
return '%s(%r)' % (self.__class__.__name__, self.base)
1306
def _get_base(self):
1307
"""Returns the directory containing the control directory."""
1310
base = property(_get_base, doc="The URL for the root of this branch.")
1312
def abspath(self, name):
1313
"""See Branch.abspath."""
1314
return self.control_files._transport.abspath(name)
1317
@deprecated_method(zero_sixteen)
1319
def get_root_id(self):
1320
"""See Branch.get_root_id."""
1321
tree = self.repository.revision_tree(self.last_revision())
1322
return tree.inventory.root.file_id
1324
def is_locked(self):
1325
return self.control_files.is_locked()
1327
def lock_write(self, token=None):
1328
repo_token = self.repository.lock_write()
1330
token = self.control_files.lock_write(token=token)
1332
self.repository.unlock()
1336
def lock_read(self):
1337
self.repository.lock_read()
1339
self.control_files.lock_read()
1341
self.repository.unlock()
1345
# TODO: test for failed two phase locks. This is known broken.
1347
self.control_files.unlock()
1349
self.repository.unlock()
1350
if not self.control_files.is_locked():
1351
# we just released the lock
1352
self._clear_cached_state()
1354
def peek_lock_mode(self):
1355
if self.control_files._lock_count == 0:
1358
return self.control_files._lock_mode
1360
def get_physical_lock_status(self):
1361
return self.control_files.get_physical_lock_status()
1364
def print_file(self, file, revision_id):
1365
"""See Branch.print_file."""
1366
return self.repository.print_file(file, revision_id)
1369
def append_revision(self, *revision_ids):
1370
"""See Branch.append_revision."""
1371
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
1372
for revision_id in revision_ids:
1373
_mod_revision.check_not_reserved_id(revision_id)
1374
mutter("add {%s} to revision-history" % revision_id)
1375
rev_history = self.revision_history()
1376
rev_history.extend(revision_ids)
1377
self.set_revision_history(rev_history)
1379
def _write_revision_history(self, history):
1380
"""Factored out of set_revision_history.
1382
This performs the actual writing to disk.
1383
It is intended to be called by BzrBranch5.set_revision_history."""
1384
self.control_files.put_bytes(
1385
'revision-history', '\n'.join(history))
1388
def set_revision_history(self, rev_history):
1389
"""See Branch.set_revision_history."""
1390
rev_history = [osutils.safe_revision_id(r) for r in rev_history]
1391
self._clear_cached_state()
1392
self._write_revision_history(rev_history)
1393
self._cache_revision_history(rev_history)
1394
for hook in Branch.hooks['set_rh']:
1395
hook(self, rev_history)
1398
def set_last_revision_info(self, revno, revision_id):
1399
revision_id = osutils.safe_revision_id(revision_id)
1400
history = self._lefthand_history(revision_id)
1401
assert len(history) == revno, '%d != %d' % (len(history), revno)
1402
self.set_revision_history(history)
1404
def _gen_revision_history(self):
1405
history = self.control_files.get('revision-history').read().split('\n')
1406
if history[-1:] == ['']:
1407
# There shouldn't be a trailing newline, but just in case.
1411
def _lefthand_history(self, revision_id, last_rev=None,
1413
# stop_revision must be a descendant of last_revision
1414
stop_graph = self.repository.get_revision_graph(revision_id)
1415
if last_rev is not None and last_rev not in stop_graph:
1416
# our previous tip is not merged into stop_revision
1417
raise errors.DivergedBranches(self, other_branch)
1418
# make a new revision history from the graph
1419
current_rev_id = revision_id
1421
while current_rev_id not in (None, _mod_revision.NULL_REVISION):
1422
new_history.append(current_rev_id)
1423
current_rev_id_parents = stop_graph[current_rev_id]
1425
current_rev_id = current_rev_id_parents[0]
1427
current_rev_id = None
1428
new_history.reverse()
1432
def generate_revision_history(self, revision_id, last_rev=None,
1434
"""Create a new revision history that will finish with revision_id.
1436
:param revision_id: the new tip to use.
1437
:param last_rev: The previous last_revision. If not None, then this
1438
must be a ancestory of revision_id, or DivergedBranches is raised.
1439
:param other_branch: The other branch that DivergedBranches should
1440
raise with respect to.
1442
revision_id = osutils.safe_revision_id(revision_id)
1443
self.set_revision_history(self._lefthand_history(revision_id,
1444
last_rev, other_branch))
1447
def update_revisions(self, other, stop_revision=None):
1448
"""See Branch.update_revisions."""
1451
if stop_revision is None:
1452
stop_revision = other.last_revision()
1453
if stop_revision is None:
1454
# if there are no commits, we're done.
1457
stop_revision = osutils.safe_revision_id(stop_revision)
1458
# whats the current last revision, before we fetch [and change it
1460
last_rev = self.last_revision()
1461
# we fetch here regardless of whether we need to so that we pickup
1463
self.fetch(other, stop_revision)
1464
my_ancestry = self.repository.get_ancestry(last_rev)
1465
if stop_revision in my_ancestry:
1466
# last_revision is a descendant of stop_revision
1468
self.generate_revision_history(stop_revision, last_rev=last_rev,
1473
def basis_tree(self):
1474
"""See Branch.basis_tree."""
1475
return self.repository.revision_tree(self.last_revision())
1477
@deprecated_method(zero_eight)
1478
def working_tree(self):
1479
"""Create a Working tree object for this branch."""
1481
from bzrlib.transport.local import LocalTransport
1482
if (self.base.find('://') != -1 or
1483
not isinstance(self._transport, LocalTransport)):
1484
raise NoWorkingTree(self.base)
1485
return self.bzrdir.open_workingtree()
1488
def pull(self, source, overwrite=False, stop_revision=None,
1489
_hook_master=None, run_hooks=True):
1492
:param _hook_master: Private parameter - set the branch to
1493
be supplied as the master to push hooks.
1494
:param run_hooks: Private parameter - if false, this branch
1495
is being called because it's the master of the primary branch,
1496
so it should not run its hooks.
1498
result = PullResult()
1499
result.source_branch = source
1500
result.target_branch = self
1503
result.old_revno, result.old_revid = self.last_revision_info()
1505
self.update_revisions(source, stop_revision)
1506
except DivergedBranches:
1510
if stop_revision is None:
1511
stop_revision = source.last_revision()
1512
self.generate_revision_history(stop_revision)
1513
result.tag_conflicts = source.tags.merge_to(self.tags)
1514
result.new_revno, result.new_revid = self.last_revision_info()
1516
result.master_branch = _hook_master
1517
result.local_branch = self
1519
result.master_branch = self
1520
result.local_branch = None
1522
for hook in Branch.hooks['post_pull']:
1528
def _get_parent_location(self):
1529
_locs = ['parent', 'pull', 'x-pull']
1532
return self.control_files.get(l).read().strip('\n')
1538
def push(self, target, overwrite=False, stop_revision=None,
1539
_override_hook_source_branch=None):
1542
This is the basic concrete implementation of push()
1544
:param _override_hook_source_branch: If specified, run
1545
the hooks passing this Branch as the source, rather than self.
1546
This is for use of RemoteBranch, where push is delegated to the
1547
underlying vfs-based Branch.
1549
# TODO: Public option to disable running hooks - should be trivial but
1553
result = self._push_with_bound_branches(target, overwrite,
1555
_override_hook_source_branch=_override_hook_source_branch)
1560
def _push_with_bound_branches(self, target, overwrite,
1562
_override_hook_source_branch=None):
1563
"""Push from self into target, and into target's master if any.
1565
This is on the base BzrBranch class even though it doesn't support
1566
bound branches because the *target* might be bound.
1569
if _override_hook_source_branch:
1570
result.source_branch = _override_hook_source_branch
1571
for hook in Branch.hooks['post_push']:
1574
bound_location = target.get_bound_location()
1575
if bound_location and target.base != bound_location:
1576
# there is a master branch.
1578
# XXX: Why the second check? Is it even supported for a branch to
1579
# be bound to itself? -- mbp 20070507
1580
master_branch = target.get_master_branch()
1581
master_branch.lock_write()
1583
# push into the master from this branch.
1584
self._basic_push(master_branch, overwrite, stop_revision)
1585
# and push into the target branch from this. Note that we push from
1586
# this branch again, because its considered the highest bandwidth
1588
result = self._basic_push(target, overwrite, stop_revision)
1589
result.master_branch = master_branch
1590
result.local_branch = target
1594
master_branch.unlock()
1597
result = self._basic_push(target, overwrite, stop_revision)
1598
# TODO: Why set master_branch and local_branch if there's no
1599
# binding? Maybe cleaner to just leave them unset? -- mbp
1601
result.master_branch = target
1602
result.local_branch = None
1606
def _basic_push(self, target, overwrite, stop_revision):
1607
"""Basic implementation of push without bound branches or hooks.
1609
Must be called with self read locked and target write locked.
1611
result = PushResult()
1612
result.source_branch = self
1613
result.target_branch = target
1614
result.old_revno, result.old_revid = target.last_revision_info()
1616
target.update_revisions(self, stop_revision)
1617
except DivergedBranches:
1621
target.set_revision_history(self.revision_history())
1622
result.tag_conflicts = self.tags.merge_to(target.tags)
1623
result.new_revno, result.new_revid = target.last_revision_info()
1626
def get_parent(self):
1627
"""See Branch.get_parent."""
1629
assert self.base[-1] == '/'
1630
parent = self._get_parent_location()
1633
# This is an old-format absolute path to a local branch
1634
# turn it into a url
1635
if parent.startswith('/'):
1636
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1638
return urlutils.join(self.base[:-1], parent)
1639
except errors.InvalidURLJoin, e:
1640
raise errors.InaccessibleParent(parent, self.base)
1642
def set_push_location(self, location):
1643
"""See Branch.set_push_location."""
1644
self.get_config().set_user_option(
1645
'push_location', location,
1646
store=_mod_config.STORE_LOCATION_NORECURSE)
1649
def set_parent(self, url):
1650
"""See Branch.set_parent."""
1651
# TODO: Maybe delete old location files?
1652
# URLs should never be unicode, even on the local fs,
1653
# FIXUP this and get_parent in a future branch format bump:
1654
# read and rewrite the file, and have the new format code read
1655
# using .get not .get_utf8. RBC 20060125
1657
if isinstance(url, unicode):
1659
url = url.encode('ascii')
1660
except UnicodeEncodeError:
1661
raise errors.InvalidURL(url,
1662
"Urls must be 7-bit ascii, "
1663
"use bzrlib.urlutils.escape")
1664
url = urlutils.relative_url(self.base, url)
1665
self._set_parent_location(url)
1667
def _set_parent_location(self, url):
1669
self.control_files._transport.delete('parent')
1671
assert isinstance(url, str)
1672
self.control_files.put_bytes('parent', url + '\n')
1674
@deprecated_function(zero_nine)
1675
def tree_config(self):
1676
"""DEPRECATED; call get_config instead.
1677
TreeConfig has become part of BranchConfig."""
1678
return TreeConfig(self)
1681
class BzrBranch5(BzrBranch):
1682
"""A format 5 branch. This supports new features over plan branches.
1684
It has support for a master_branch which is the data for bound branches.
1692
super(BzrBranch5, self).__init__(_format=_format,
1693
_control_files=_control_files,
1695
_repository=_repository)
1698
def pull(self, source, overwrite=False, stop_revision=None,
1700
"""Pull from source into self, updating my master if any.
1702
:param run_hooks: Private parameter - if false, this branch
1703
is being called because it's the master of the primary branch,
1704
so it should not run its hooks.
1706
bound_location = self.get_bound_location()
1707
master_branch = None
1708
if bound_location and source.base != bound_location:
1709
# not pulling from master, so we need to update master.
1710
master_branch = self.get_master_branch()
1711
master_branch.lock_write()
1714
# pull from source into master.
1715
master_branch.pull(source, overwrite, stop_revision,
1717
return super(BzrBranch5, self).pull(source, overwrite,
1718
stop_revision, _hook_master=master_branch,
1719
run_hooks=run_hooks)
1722
master_branch.unlock()
1724
def get_bound_location(self):
1726
return self.control_files.get_utf8('bound').read()[:-1]
1727
except errors.NoSuchFile:
1731
def get_master_branch(self):
1732
"""Return the branch we are bound to.
1734
:return: Either a Branch, or None
1736
This could memoise the branch, but if thats done
1737
it must be revalidated on each new lock.
1738
So for now we just don't memoise it.
1739
# RBC 20060304 review this decision.
1741
bound_loc = self.get_bound_location()
1745
return Branch.open(bound_loc)
1746
except (errors.NotBranchError, errors.ConnectionError), e:
1747
raise errors.BoundBranchConnectionFailure(
1751
def set_bound_location(self, location):
1752
"""Set the target where this branch is bound to.
1754
:param location: URL to the target branch
1757
self.control_files.put_utf8('bound', location+'\n')
1760
self.control_files._transport.delete('bound')
738
file(os.path.join(self.base, f), 'w').write('content of %s' % f)
745
"""Destroy the test branch, removing the scratch directory."""
747
mutter("delete ScratchBranch %s" % self.base)
748
shutil.rmtree(self.base)
750
# Work around for shutil.rmtree failing on Windows when
751
# readonly files are encountered
752
mutter("hit exception in destroying ScratchBranch: %s" % e)
753
for root, dirs, files in os.walk(self.base, topdown=False):
755
os.chmod(os.path.join(root, name), 0700)
756
shutil.rmtree(self.base)
761
######################################################################
765
def is_control_file(filename):
766
## FIXME: better check
767
filename = os.path.normpath(filename)
768
while filename != '':
769
head, tail = os.path.split(filename)
770
## mutter('check %r for control file' % ((head, tail), ))
771
if tail == bzrlib.BZRDIR:
1766
def bind(self, other):
1767
"""Bind this branch to the branch other.
1769
This does not push or pull data between the branches, though it does
1770
check for divergence to raise an error when the branches are not
1771
either the same, or one a prefix of the other. That behaviour may not
1772
be useful, so that check may be removed in future.
1774
:param other: The branch to bind to
1777
# TODO: jam 20051230 Consider checking if the target is bound
1778
# It is debatable whether you should be able to bind to
1779
# a branch which is itself bound.
1780
# Committing is obviously forbidden,
1781
# but binding itself may not be.
1782
# Since we *have* to check at commit time, we don't
1783
# *need* to check here
1785
# we want to raise diverged if:
1786
# last_rev is not in the other_last_rev history, AND
1787
# other_last_rev is not in our history, and do it without pulling
1789
last_rev = self.last_revision()
1790
if last_rev is not None:
1793
other_last_rev = other.last_revision()
1794
if other_last_rev is not None:
1795
# neither branch is new, we have to do some work to
1796
# ascertain diversion.
1797
remote_graph = other.repository.get_revision_graph(
1799
local_graph = self.repository.get_revision_graph(last_rev)
1800
if (last_rev not in remote_graph and
1801
other_last_rev not in local_graph):
1802
raise errors.DivergedBranches(self, other)
1805
self.set_bound_location(other.base)
1809
"""If bound, unbind"""
1810
return self.set_bound_location(None)
1814
"""Synchronise this branch with the master branch if any.
1816
:return: None or the last_revision that was pivoted out during the
1819
master = self.get_master_branch()
1820
if master is not None:
1821
old_tip = self.last_revision()
1822
self.pull(master, overwrite=True)
1823
if old_tip in self.repository.get_ancestry(self.last_revision()):
1829
class BzrBranchExperimental(BzrBranch5):
1830
"""Bzr experimental branch format
1833
- a revision-history file.
1835
- a lock dir guarding the branch itself
1836
- all of this stored in a branch/ subdirectory
1837
- works with shared repositories.
1838
- a tag dictionary in the branch
1840
This format is new in bzr 0.15, but shouldn't be used for real data,
1843
This class acts as it's own BranchFormat.
1846
_matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1849
def get_format_string(cls):
1850
"""See BranchFormat.get_format_string()."""
1851
return "Bazaar-NG branch format experimental\n"
1854
def get_format_description(cls):
1855
"""See BranchFormat.get_format_description()."""
1856
return "Experimental branch format"
1859
def get_reference(cls, a_bzrdir):
1860
"""Get the target reference of the branch in a_bzrdir.
1862
format probing must have been completed before calling
1863
this method - it is assumed that the format of the branch
1864
in a_bzrdir is correct.
1866
:param a_bzrdir: The bzrdir to get the branch data from.
1867
:return: None if the branch is not a reference branch.
1872
def _initialize_control_files(cls, a_bzrdir, utf8_files, lock_filename,
1874
branch_transport = a_bzrdir.get_branch_transport(cls)
1875
control_files = lockable_files.LockableFiles(branch_transport,
1876
lock_filename, lock_class)
1877
control_files.create_lock()
1878
control_files.lock_write()
1880
for filename, content in utf8_files:
1881
control_files.put_utf8(filename, content)
1883
control_files.unlock()
1886
def initialize(cls, a_bzrdir):
1887
"""Create a branch of this format in a_bzrdir."""
1888
utf8_files = [('format', cls.get_format_string()),
1889
('revision-history', ''),
1890
('branch-name', ''),
1893
cls._initialize_control_files(a_bzrdir, utf8_files,
1894
'lock', lockdir.LockDir)
1895
return cls.open(a_bzrdir, _found=True)
1898
def open(cls, a_bzrdir, _found=False):
1899
"""Return the branch object for a_bzrdir
1901
_found is a private parameter, do not use it. It is used to indicate
1902
if format probing has already be done.
1905
format = BranchFormat.find_format(a_bzrdir)
1906
assert format.__class__ == cls
1907
transport = a_bzrdir.get_branch_transport(None)
1908
control_files = lockable_files.LockableFiles(transport, 'lock',
1910
return cls(_format=cls,
1911
_control_files=control_files,
1913
_repository=a_bzrdir.find_repository())
1916
def is_supported(cls):
1919
def _make_tags(self):
1920
return BasicTags(self)
1923
def supports_tags(cls):
1927
BranchFormat.register_format(BzrBranchExperimental)
1930
class BzrBranch6(BzrBranch5):
1933
def last_revision_info(self):
1934
revision_string = self.control_files.get('last-revision').read()
1935
revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
1936
revision_id = cache_utf8.get_cached_utf8(revision_id)
1938
return revno, revision_id
1940
def last_revision(self):
1941
"""Return last revision id, or None"""
1942
revision_id = self.last_revision_info()[1]
1943
if revision_id == _mod_revision.NULL_REVISION:
1947
def _write_last_revision_info(self, revno, revision_id):
1948
"""Simply write out the revision id, with no checks.
1950
Use set_last_revision_info to perform this safely.
1952
Does not update the revision_history cache.
1953
Intended to be called by set_last_revision_info and
1954
_write_revision_history.
1956
if revision_id is None:
1957
revision_id = 'null:'
1958
out_string = '%d %s\n' % (revno, revision_id)
1959
self.control_files.put_bytes('last-revision', out_string)
1962
def set_last_revision_info(self, revno, revision_id):
1963
revision_id = osutils.safe_revision_id(revision_id)
1964
if self._get_append_revisions_only():
1965
self._check_history_violation(revision_id)
1966
self._write_last_revision_info(revno, revision_id)
1967
self._clear_cached_state()
1969
def _check_history_violation(self, revision_id):
1970
last_revision = self.last_revision()
1971
if last_revision is None:
1973
if last_revision not in self._lefthand_history(revision_id):
1974
raise errors.AppendRevisionsOnlyViolation(self.base)
1976
def _gen_revision_history(self):
1977
"""Generate the revision history from last revision
1979
history = list(self.repository.iter_reverse_revision_history(
1980
self.last_revision()))
1984
def _write_revision_history(self, history):
1985
"""Factored out of set_revision_history.
1987
This performs the actual writing to disk, with format-specific checks.
1988
It is intended to be called by BzrBranch5.set_revision_history.
1990
if len(history) == 0:
1991
last_revision = 'null:'
1993
if history != self._lefthand_history(history[-1]):
1994
raise errors.NotLefthandHistory(history)
1995
last_revision = history[-1]
1996
if self._get_append_revisions_only():
1997
self._check_history_violation(last_revision)
1998
self._write_last_revision_info(len(history), last_revision)
2001
def append_revision(self, *revision_ids):
2002
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
2003
if len(revision_ids) == 0:
2005
prev_revno, prev_revision = self.last_revision_info()
2006
for revision in self.repository.get_revisions(revision_ids):
2007
if prev_revision == _mod_revision.NULL_REVISION:
2008
if revision.parent_ids != []:
2009
raise errors.NotLeftParentDescendant(self, prev_revision,
2010
revision.revision_id)
2012
if revision.parent_ids[0] != prev_revision:
2013
raise errors.NotLeftParentDescendant(self, prev_revision,
2014
revision.revision_id)
2015
prev_revision = revision.revision_id
2016
self.set_last_revision_info(prev_revno + len(revision_ids),
2020
def _set_parent_location(self, url):
2021
"""Set the parent branch"""
2022
self._set_config_location('parent_location', url, make_relative=True)
2025
def _get_parent_location(self):
2026
"""Set the parent branch"""
2027
return self._get_config_location('parent_location')
2029
def set_push_location(self, location):
2030
"""See Branch.set_push_location."""
2031
self._set_config_location('push_location', location)
2033
def set_bound_location(self, location):
2034
"""See Branch.set_push_location."""
2036
config = self.get_config()
2037
if location is None:
2038
if config.get_user_option('bound') != 'True':
2041
config.set_user_option('bound', 'False')
2044
self._set_config_location('bound_location', location,
2046
config.set_user_option('bound', 'True')
2049
def _get_bound_location(self, bound):
2050
"""Return the bound location in the config file.
2052
Return None if the bound parameter does not match"""
2053
config = self.get_config()
2054
config_bound = (config.get_user_option('bound') == 'True')
2055
if config_bound != bound:
2057
return self._get_config_location('bound_location', config=config)
2059
def get_bound_location(self):
2060
"""See Branch.set_push_location."""
2061
return self._get_bound_location(True)
2063
def get_old_bound_location(self):
2064
"""See Branch.get_old_bound_location"""
2065
return self._get_bound_location(False)
2067
def set_append_revisions_only(self, enabled):
2072
self.get_config().set_user_option('append_revisions_only', value)
2074
def _get_append_revisions_only(self):
2075
value = self.get_config().get_user_option('append_revisions_only')
2076
return value == 'True'
2078
def _synchronize_history(self, destination, revision_id):
2079
"""Synchronize last revision and revision history between branches.
2081
This version is most efficient when the destination is also a
2082
BzrBranch6, but works for BzrBranch5, as long as the destination's
2083
repository contains all the lefthand ancestors of the intended
2084
last_revision. If not, set_last_revision_info will fail.
2086
:param destination: The branch to copy the history into
2087
:param revision_id: The revision-id to truncate history at. May
2088
be None to copy complete history.
2090
if revision_id is None:
2091
revno, revision_id = self.last_revision_info()
2093
# To figure out the revno for a random revision, we need to build
2094
# the revision history, and count its length.
2095
# We don't care about the order, just how long it is.
2096
# Alternatively, we could start at the current location, and count
2097
# backwards. But there is no guarantee that we will find it since
2098
# it may be a merged revision.
2099
revno = len(list(self.repository.iter_reverse_revision_history(
2101
destination.set_last_revision_info(revno, revision_id)
2103
def _make_tags(self):
2104
return BasicTags(self)
2107
class BranchTestProviderAdapter(object):
2108
"""A tool to generate a suite testing multiple branch formats at once.
2110
This is done by copying the test once for each transport and injecting
2111
the transport_server, transport_readonly_server, and branch_format
2112
classes into each copy. Each copy is also given a new id() to make it
2116
def __init__(self, transport_server, transport_readonly_server, formats,
2117
vfs_transport_factory=None):
2118
self._transport_server = transport_server
2119
self._transport_readonly_server = transport_readonly_server
2120
self._formats = formats
2122
def adapt(self, test):
2123
result = TestSuite()
2124
for branch_format, bzrdir_format in self._formats:
2125
new_test = deepcopy(test)
2126
new_test.transport_server = self._transport_server
2127
new_test.transport_readonly_server = self._transport_readonly_server
2128
new_test.bzrdir_format = bzrdir_format
2129
new_test.branch_format = branch_format
2130
def make_new_test_id():
2131
# the format can be either a class or an instance
2132
name = getattr(branch_format, '__name__',
2133
branch_format.__class__.__name__)
2134
new_id = "%s(%s)" % (new_test.id(), name)
2135
return lambda: new_id
2136
new_test.id = make_new_test_id()
2137
result.addTest(new_test)
2141
######################################################################
2142
# results of operations
2145
class _Result(object):
2147
def _show_tag_conficts(self, to_file):
2148
if not getattr(self, 'tag_conflicts', None):
2150
to_file.write('Conflicting tags:\n')
2151
for name, value1, value2 in self.tag_conflicts:
2152
to_file.write(' %s\n' % (name, ))
2155
class PullResult(_Result):
2156
"""Result of a Branch.pull operation.
2158
:ivar old_revno: Revision number before pull.
2159
:ivar new_revno: Revision number after pull.
2160
:ivar old_revid: Tip revision id before pull.
2161
:ivar new_revid: Tip revision id after pull.
2162
:ivar source_branch: Source (local) branch object.
2163
:ivar master_branch: Master branch of the target, or None.
2164
:ivar target_branch: Target/destination branch object.
2168
# DEPRECATED: pull used to return the change in revno
2169
return self.new_revno - self.old_revno
2171
def report(self, to_file):
2172
if self.old_revid == self.new_revid:
2173
to_file.write('No revisions to pull.\n')
2175
to_file.write('Now on revision %d.\n' % self.new_revno)
2176
self._show_tag_conficts(to_file)
2179
class PushResult(_Result):
2180
"""Result of a Branch.push operation.
2182
:ivar old_revno: Revision number before push.
2183
:ivar new_revno: Revision number after push.
2184
:ivar old_revid: Tip revision id before push.
2185
:ivar new_revid: Tip revision id after push.
2186
:ivar source_branch: Source branch object.
2187
:ivar master_branch: Master branch of the target, or None.
2188
:ivar target_branch: Target/destination branch object.
2192
# DEPRECATED: push used to return the change in revno
2193
return self.new_revno - self.old_revno
2195
def report(self, to_file):
2196
"""Write a human-readable description of the result."""
2197
if self.old_revid == self.new_revid:
2198
to_file.write('No new revisions to push.\n')
2200
to_file.write('Pushed up to revision %d.\n' % self.new_revno)
2201
self._show_tag_conficts(to_file)
2204
class BranchCheckResult(object):
2205
"""Results of checking branch consistency.
2210
def __init__(self, branch):
2211
self.branch = branch
2213
def report_results(self, verbose):
2214
"""Report the check results via trace.note.
2216
:param verbose: Requests more detailed display of what was checked,
2219
note('checked branch %s format %s',
2221
self.branch._format)
2224
class Converter5to6(object):
2225
"""Perform an in-place upgrade of format 5 to format 6"""
2227
def convert(self, branch):
2228
# Data for 5 and 6 can peacefully coexist.
2229
format = BzrBranchFormat6()
2230
new_branch = format.open(branch.bzrdir, _found=True)
2232
# Copy source data into target
2233
new_branch.set_last_revision_info(*branch.last_revision_info())
2234
new_branch.set_parent(branch.get_parent())
2235
new_branch.set_bound_location(branch.get_bound_location())
2236
new_branch.set_push_location(branch.get_push_location())
2238
# New branch has no tags by default
2239
new_branch.tags._set_tag_dict({})
2241
# Copying done; now update target format
2242
new_branch.control_files.put_utf8('format',
2243
format.get_format_string())
2245
# Clean up old files
2246
new_branch.control_files._transport.delete('revision-history')
2248
branch.set_parent(None)
2251
branch.set_bound_location(None)
780
def gen_file_id(name):
781
"""Return new file id.
783
This should probably generate proper UUIDs, but for the moment we
784
cope with just randomness because running uuidgen every time is
786
idx = name.rfind('/')
788
name = name[idx+1 : ]
789
idx = name.rfind('\\')
791
name = name[idx+1 : ]
793
name = name.lstrip('.')
795
s = hexlify(rand_bytes(8))
796
return '-'.join((name, compact_date(time.time()), s))