1
# Copyright (C) 2005, 2006 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 copy import deepcopy
19
from cStringIO import StringIO
24
from unittest import TestSuite
25
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
28
import bzrlib.bzrdir as bzrdir
29
from bzrlib.config import TreeConfig
30
from bzrlib.decorators import needs_read_lock, needs_write_lock
31
from bzrlib.delta import compare_trees
32
import bzrlib.errors as errors
33
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
34
NoSuchRevision, HistoryMissing, NotBranchError,
35
DivergedBranches, LockError,
36
UninitializableFormat,
38
UnlistableBranch, NoSuchFile, NotVersionedError,
40
import bzrlib.inventory as inventory
41
from bzrlib.inventory import Inventory
42
from bzrlib.lockable_files import LockableFiles, TransportLock
43
from bzrlib.lockdir import LockDir
44
from bzrlib.osutils import (isdir, quotefn,
45
rename, splitpath, sha_file,
46
file_kind, abspath, normpath, pathjoin,
49
from bzrlib.textui import show_status
50
from bzrlib.trace import mutter, note
51
from bzrlib.tree import EmptyTree, RevisionTree
52
from bzrlib.repository import Repository
53
from bzrlib.revision import (
54
get_intervening_revisions,
59
from bzrlib.store import copy_all
60
from bzrlib.symbol_versioning import *
61
import bzrlib.transactions as transactions
62
from bzrlib.transport import Transport, get_transport
63
from bzrlib.tree import EmptyTree, RevisionTree
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-NG branch, format 6\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, WorkingTree
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
36
from diff import diff_trees
38
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
39
## TODO: Maybe include checks for common corruption of newlines, etc?
43
def find_branch_root(f=None):
44
"""Find the branch root enclosing f, or pwd.
46
It is not necessary that f exists.
48
Basically we keep looking up until we find the control directory or
52
elif hasattr(os.path, 'realpath'):
53
f = os.path.realpath(f)
55
f = os.path.abspath(f)
60
if os.path.exists(os.path.join(f, bzrlib.BZRDIR)):
62
head, tail = os.path.split(f)
64
# reached the root, whatever that may be
65
raise BzrError('%r is not in a branch' % orig_f)
82
70
######################################################################
86
74
"""Branch holding a history of revisions.
89
Base directory/url of the branch.
77
Base directory of the branch.
91
# this is really an instance variable - FIXME move it there
95
def __init__(self, *ignored, **ignored_too):
96
raise NotImplementedError('The Branch class is abstract')
99
@deprecated_method(zero_eight)
100
def open_downlevel(base):
101
"""Open a branch which may be of an old format."""
102
return Branch.open(base, _unsupported=True)
105
def open(base, _unsupported=False):
106
"""Open the repository rooted at base.
108
For instance, if the repository is at URL/.bzr/repository,
109
Repository.open(URL) -> a Repository instance.
111
control = bzrdir.BzrDir.open(base, _unsupported)
112
return control.open_branch(_unsupported)
115
def open_containing(url):
116
"""Open an existing branch which contains url.
118
This probes for a branch at url, and searches upwards from there.
120
Basically we keep looking up until we find the control directory or
121
run into the root. If there isn't one, raises NotBranchError.
122
If there is one and it is either an unrecognised format or an unsupported
123
format, UnknownFormatError or UnsupportedFormatError are raised.
124
If there is one, it is returned, along with the unused portion of url.
126
control, relpath = bzrdir.BzrDir.open_containing(url)
127
return control.open_branch(), relpath
130
@deprecated_function(zero_eight)
131
def initialize(base):
132
"""Create a new working tree and branch, rooted at 'base' (url)
134
NOTE: This will soon be deprecated in favour of creation
137
return bzrdir.BzrDir.create_standalone_workingtree(base).branch
139
def setup_caching(self, cache_root):
140
"""Subclasses that care about caching should override this, and set
141
up cached stores located under cache_root.
143
# seems to be unused, 2006-01-13 mbp
144
warn('%s is deprecated' % self.setup_caching)
145
self.cache_root = cache_root
148
cfg = self.tree_config()
149
return cfg.get_option(u"nickname", default=self.base.split('/')[-2])
151
def _set_nick(self, nick):
152
cfg = self.tree_config()
153
cfg.set_option(nick, "nickname")
154
assert cfg.get_option("nickname") == nick
156
nick = property(_get_nick, _set_nick)
159
raise NotImplementedError('is_locked is abstract')
161
def lock_write(self):
162
raise NotImplementedError('lock_write is abstract')
165
raise NotImplementedError('lock_read is abstract')
168
raise NotImplementedError('unlock is abstract')
170
def peek_lock_mode(self):
171
"""Return lock mode for the Branch: 'r', 'w' or None"""
172
raise NotImplementedError(self.peek_lock_mode)
174
def get_physical_lock_status(self):
175
raise NotImplementedError('get_physical_lock_status is abstract')
81
def __init__(self, base, init=False, find_root=True, lock_mode='w'):
82
"""Create new branch object at a particular location.
84
base -- Base directory for the branch.
86
init -- If True, create new control files in a previously
87
unversioned directory. If False, the branch must already
90
find_root -- If true and init is false, find the root of the
91
existing branch containing base.
93
In the test suite, creation of new trees is tested using the
94
`ScratchBranch` class.
97
self.base = os.path.realpath(base)
100
self.base = find_branch_root(base)
102
self.base = os.path.realpath(base)
103
if not isdir(self.controlfilename('.')):
104
bailout("not a bzr branch: %s" % quotefn(base),
105
['use "bzr init" to initialize a new working tree',
106
'current bzr can only operate from top-of-tree'])
110
self.text_store = ImmutableStore(self.controlfilename('text-store'))
111
self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
112
self.inventory_store = ImmutableStore(self.controlfilename('inventory-store'))
116
return '%s(%r)' % (self.__class__.__name__, self.base)
123
def lock(self, mode='w'):
124
"""Lock the on-disk branch, excluding other processes."""
130
om = os.O_WRONLY | os.O_CREAT
135
raise BzrError("invalid locking mode %r" % mode)
137
# XXX: Old branches might not have the lock file, and
138
# won't get one until someone does a write-mode command on
139
# them or creates it by hand.
141
lockfile = os.open(self.controlfilename('branch-lock'), om)
142
fcntl.lockf(lockfile, lm)
144
fcntl.lockf(lockfile, fcntl.LOCK_UN)
146
self._lockmode = None
148
self._lockmode = mode
150
warning("please write a locking method for platform %r" % sys.platform)
152
self._lockmode = None
154
self._lockmode = mode
157
def _need_readlock(self):
158
if self._lockmode not in ['r', 'w']:
159
raise BzrError('need read lock on branch, only have %r' % self._lockmode)
161
def _need_writelock(self):
162
if self._lockmode not in ['w']:
163
raise BzrError('need write lock on branch, only have %r' % self._lockmode)
177
166
def abspath(self, name):
178
"""Return absolute filename for something in the branch
180
XXX: Robert Collins 20051017 what is this used for? why is it a branch
181
method and not a tree method.
183
raise NotImplementedError('abspath is abstract')
185
def bind(self, other):
186
"""Bind the local branch the other branch.
188
:param other: The branch to bind to
191
raise errors.UpgradeRequired(self.base)
194
def fetch(self, from_branch, last_revision=None, pb=None):
195
"""Copy revisions from from_branch into this branch.
197
:param from_branch: Where to copy from.
198
:param last_revision: What revision to stop at (None for at the end
200
:param pb: An optional progress bar to use.
202
Returns the copied revision count and the failed revisions in a tuple:
205
if self.base == from_branch.base:
208
nested_pb = bzrlib.ui.ui_factory.nested_progress_bar()
167
"""Return absolute filename for something in the branch"""
168
return os.path.join(self.base, name)
171
def relpath(self, path):
172
"""Return path relative to this branch of something inside it.
174
Raises an error if path is not in this branch."""
175
rp = os.path.realpath(path)
177
if not rp.startswith(self.base):
178
bailout("path %r is not within branch %r" % (rp, self.base))
179
rp = rp[len(self.base):]
180
rp = rp.lstrip(os.sep)
184
def controlfilename(self, file_or_path):
185
"""Return location relative to branch."""
186
if isinstance(file_or_path, types.StringTypes):
187
file_or_path = [file_or_path]
188
return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
191
def controlfile(self, file_or_path, mode='r'):
192
"""Open a control file for this branch.
194
There are two classes of file in the control directory: text
195
and binary. binary files are untranslated byte streams. Text
196
control files are stored with Unix newlines and in UTF-8, even
197
if the platform or locale defaults are different.
200
fn = self.controlfilename(file_or_path)
202
if mode == 'rb' or mode == 'wb':
203
return file(fn, mode)
204
elif mode == 'r' or mode == 'w':
205
# open in binary mode anyhow so there's no newline translation;
206
# codecs uses line buffering by default; don't want that.
208
return codecs.open(fn, mode + 'b', 'utf-8',
213
from_branch.lock_read()
215
if last_revision is None:
216
pb.update('get source history')
217
from_history = from_branch.revision_history()
219
last_revision = from_history[-1]
221
# no history in the source branch
222
last_revision = NULL_REVISION
223
return self.repository.fetch(from_branch.repository,
224
revision_id=last_revision,
227
if nested_pb is not None:
231
def get_bound_location(self):
232
"""Return the URL of the branch we are bound to.
234
Older format branches cannot bind, please be sure to use a metadir
239
def get_master_branch(self):
240
"""Return the branch we are bound to.
211
raise BzrError("invalid controlfile mode %r" % mode)
215
def _make_control(self):
216
os.mkdir(self.controlfilename([]))
217
self.controlfile('README', 'w').write(
218
"This is a Bazaar-NG control directory.\n"
219
"Do not change any files in this directory.")
220
self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT)
221
for d in ('text-store', 'inventory-store', 'revision-store'):
222
os.mkdir(self.controlfilename(d))
223
for f in ('revision-history', 'merged-patches',
224
'pending-merged-patches', 'branch-name',
226
self.controlfile(f, 'w').write('')
227
mutter('created control directory in ' + self.base)
228
Inventory().write_xml(self.controlfile('inventory','w'))
231
def _check_format(self):
232
"""Check this branch format is supported.
234
The current tool only supports the current unstable format.
236
In the future, we might need different in-memory Branch
237
classes to support downlevel branches. But not yet.
239
# This ignores newlines so that we can open branches created
240
# on Windows from Linux and so on. I think it might be better
241
# to always make all internal files in unix format.
242
fmt = self.controlfile('branch-format', 'r').read()
243
fmt.replace('\r\n', '')
244
if fmt != BZR_BRANCH_FORMAT:
245
bailout('sorry, branch format %r not supported' % fmt,
246
['use a different bzr version',
247
'or remove the .bzr directory and "bzr init" again'])
250
def read_working_inventory(self):
251
"""Read the working inventory."""
252
self._need_readlock()
254
# ElementTree does its own conversion from UTF-8, so open in
256
inv = Inventory.read_xml(self.controlfile('inventory', 'rb'))
257
mutter("loaded inventory of %d items in %f"
258
% (len(inv), time.time() - before))
262
def _write_inventory(self, inv):
263
"""Update the working inventory.
265
That is to say, the inventory describing changes underway, that
266
will be committed to the next revision.
268
self._need_writelock()
269
## TODO: factor out to atomicfile? is rename safe on windows?
270
## TODO: Maybe some kind of clean/dirty marker on inventory?
271
tmpfname = self.controlfilename('inventory.tmp')
272
tmpf = file(tmpfname, 'wb')
275
inv_fname = self.controlfilename('inventory')
276
if sys.platform == 'win32':
278
os.rename(tmpfname, inv_fname)
279
mutter('wrote working inventory')
282
inventory = property(read_working_inventory, _write_inventory, None,
283
"""Inventory for the working copy.""")
286
def add(self, files, verbose=False):
287
"""Make files versioned.
289
Note that the command line normally calls smart_add instead.
291
This puts the files in the Added state, so that they will be
292
recorded by the next commit.
294
TODO: Perhaps have an option to add the ids even if the files do
297
TODO: Perhaps return the ids of the files? But then again it
298
is easy to retrieve them if they're needed.
300
TODO: Option to specify file id.
302
TODO: Adding a directory should optionally recurse down and
303
add all non-ignored children. Perhaps do that in a
306
>>> b = ScratchBranch(files=['foo'])
307
>>> 'foo' in b.unknowns()
312
>>> 'foo' in b.unknowns()
314
>>> bool(b.inventory.path2id('foo'))
320
Traceback (most recent call last):
322
BzrError: ('foo is already versioned', [])
324
>>> b.add(['nothere'])
325
Traceback (most recent call last):
326
BzrError: ('cannot add: not a regular file or directory: nothere', [])
328
self._need_writelock()
330
# TODO: Re-adding a file that is removed in the working copy
331
# should probably put it back with the previous ID.
332
if isinstance(files, types.StringTypes):
242
:return: Either a Branch, or None
246
def get_root_id(self):
247
"""Return the id of this branches root"""
248
raise NotImplementedError('get_root_id is abstract')
250
def print_file(self, file, revision_id):
335
inv = self.read_working_inventory()
337
if is_control_file(f):
338
bailout("cannot add control file %s" % quotefn(f))
343
bailout("cannot add top-level %r" % f)
345
fullpath = os.path.normpath(self.abspath(f))
348
kind = file_kind(fullpath)
350
# maybe something better?
351
bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
353
if kind != 'file' and kind != 'directory':
354
bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
356
file_id = gen_file_id(f)
357
inv.add_path(f, kind=kind, file_id=file_id)
360
show_status('A', kind, quotefn(f))
362
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
364
self._write_inventory(inv)
367
def print_file(self, file, revno):
251
368
"""Print `file` to stdout."""
252
raise NotImplementedError('print_file is abstract')
254
def append_revision(self, *revision_ids):
255
raise NotImplementedError('append_revision is abstract')
257
def set_revision_history(self, rev_history):
258
raise NotImplementedError('set_revision_history is abstract')
369
self._need_readlock()
370
tree = self.revision_tree(self.lookup_revision(revno))
371
# use inventory as it was in that revision
372
file_id = tree.inventory.path2id(file)
374
bailout("%r is not present in revision %d" % (file, revno))
375
tree.print_file(file_id)
378
def remove(self, files, verbose=False):
379
"""Mark nominated files for removal from the inventory.
381
This does not remove their text. This does not run on
383
TODO: Refuse to remove modified files unless --force is given?
385
>>> b = ScratchBranch(files=['foo'])
387
>>> b.inventory.has_filename('foo')
390
>>> b.working_tree().has_filename('foo')
392
>>> b.inventory.has_filename('foo')
395
>>> b = ScratchBranch(files=['foo'])
400
>>> b.inventory.has_filename('foo')
402
>>> b.basis_tree().has_filename('foo')
404
>>> b.working_tree().has_filename('foo')
407
TODO: Do something useful with directories.
409
TODO: Should this remove the text or not? Tough call; not
410
removing may be useful and the user can just use use rm, and
411
is the opposite of add. Removing it is consistent with most
412
other tools. Maybe an option.
414
## TODO: Normalize names
415
## TODO: Remove nested loops; better scalability
416
self._need_writelock()
418
if isinstance(files, types.StringTypes):
421
tree = self.working_tree()
424
# do this before any modifications
428
bailout("cannot remove unversioned file %s" % quotefn(f))
429
mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
431
# having remove it, it must be either ignored or unknown
432
if tree.is_ignored(f):
436
show_status(new_status, inv[fid].kind, quotefn(f))
439
self._write_inventory(inv)
443
"""Return all unknown files.
445
These are files in the working directory that are not versioned or
446
control files or ignored.
448
>>> b = ScratchBranch(files=['foo', 'foo~'])
449
>>> list(b.unknowns())
452
>>> list(b.unknowns())
455
>>> list(b.unknowns())
458
return self.working_tree().unknowns()
461
def commit(self, message, timestamp=None, timezone=None,
464
"""Commit working copy as a new revision.
466
The basic approach is to add all the file texts into the
467
store, then the inventory, then make a new revision pointing
468
to that inventory and store that.
470
This is not quite safe if the working copy changes during the
471
commit; for the moment that is simply not allowed. A better
472
approach is to make a temporary copy of the files before
473
computing their hashes, and then add those hashes in turn to
474
the inventory. This should mean at least that there are no
475
broken hash pointers. There is no way we can get a snapshot
476
of the whole directory at an instant. This would also have to
477
be robust against files disappearing, moving, etc. So the
478
whole thing is a bit hard.
480
timestamp -- if not None, seconds-since-epoch for a
481
postdated/predated commit.
483
self._need_writelock()
485
## TODO: Show branch names
487
# TODO: Don't commit if there are no changes, unless forced?
489
# First walk over the working inventory; and both update that
490
# and also build a new revision inventory. The revision
491
# inventory needs to hold the text-id, sha1 and size of the
492
# actual file versions committed in the revision. (These are
493
# not present in the working inventory.) We also need to
494
# detect missing/deleted files, and remove them from the
497
work_inv = self.read_working_inventory()
499
basis = self.basis_tree()
500
basis_inv = basis.inventory
502
for path, entry in work_inv.iter_entries():
503
## TODO: Cope with files that have gone missing.
505
## TODO: Check that the file kind has not changed from the previous
506
## revision of this file (if any).
510
p = self.abspath(path)
511
file_id = entry.file_id
512
mutter('commit prep file %s, id %r ' % (p, file_id))
514
if not os.path.exists(p):
515
mutter(" file is missing, removing from inventory")
517
show_status('D', entry.kind, quotefn(path))
518
missing_ids.append(file_id)
521
# TODO: Handle files that have been deleted
523
# TODO: Maybe a special case for empty files? Seems a
524
# waste to store them many times.
528
if basis_inv.has_id(file_id):
529
old_kind = basis_inv[file_id].kind
530
if old_kind != entry.kind:
531
bailout("entry %r changed kind from %r to %r"
532
% (file_id, old_kind, entry.kind))
534
if entry.kind == 'directory':
536
bailout("%s is entered as directory but not a directory" % quotefn(p))
537
elif entry.kind == 'file':
539
bailout("%s is entered as file but is not a file" % quotefn(p))
541
content = file(p, 'rb').read()
543
entry.text_sha1 = sha_string(content)
544
entry.text_size = len(content)
546
old_ie = basis_inv.has_id(file_id) and basis_inv[file_id]
548
and (old_ie.text_size == entry.text_size)
549
and (old_ie.text_sha1 == entry.text_sha1)):
550
## assert content == basis.get_file(file_id).read()
551
entry.text_id = basis_inv[file_id].text_id
552
mutter(' unchanged from previous text_id {%s}' %
556
entry.text_id = gen_file_id(entry.name)
557
self.text_store.add(content, entry.text_id)
558
mutter(' stored with text_id {%s}' % entry.text_id)
562
elif (old_ie.name == entry.name
563
and old_ie.parent_id == entry.parent_id):
568
show_status(state, entry.kind, quotefn(path))
570
for file_id in missing_ids:
571
# have to do this later so we don't mess up the iterator.
572
# since parents may be removed before their children we
575
# FIXME: There's probably a better way to do this; perhaps
576
# the workingtree should know how to filter itself.
577
if work_inv.has_id(file_id):
578
del work_inv[file_id]
581
inv_id = rev_id = _gen_revision_id(time.time())
583
inv_tmp = tempfile.TemporaryFile()
584
inv.write_xml(inv_tmp)
586
self.inventory_store.add(inv_tmp, inv_id)
587
mutter('new inventory_id is {%s}' % inv_id)
589
self._write_inventory(work_inv)
591
if timestamp == None:
592
timestamp = time.time()
594
if committer == None:
595
committer = username()
598
timezone = local_time_offset()
600
mutter("building commit log message")
601
rev = Revision(timestamp=timestamp,
604
precursor = self.last_patch(),
609
rev_tmp = tempfile.TemporaryFile()
610
rev.write_xml(rev_tmp)
612
self.revision_store.add(rev_tmp, rev_id)
613
mutter("new revision_id is {%s}" % rev_id)
615
## XXX: Everything up to here can simply be orphaned if we abort
616
## the commit; it will leave junk files behind but that doesn't
619
## TODO: Read back the just-generated changeset, and make sure it
620
## applies and recreates the right state.
622
## TODO: Also calculate and store the inventory SHA1
623
mutter("committing patch r%d" % (self.revno() + 1))
626
self.append_revision(rev_id)
629
note("commited r%d" % self.revno())
632
def append_revision(self, revision_id):
633
mutter("add {%s} to revision-history" % revision_id)
634
rev_history = self.revision_history()
636
tmprhname = self.controlfilename('revision-history.tmp')
637
rhname = self.controlfilename('revision-history')
639
f = file(tmprhname, 'wt')
640
rev_history.append(revision_id)
641
f.write('\n'.join(rev_history))
645
if sys.platform == 'win32':
647
os.rename(tmprhname, rhname)
651
def get_revision(self, revision_id):
652
"""Return the Revision object for a named revision"""
653
self._need_readlock()
654
r = Revision.read_xml(self.revision_store[revision_id])
655
assert r.revision_id == revision_id
659
def get_inventory(self, inventory_id):
660
"""Get Inventory object by hash.
662
TODO: Perhaps for this and similar methods, take a revision
663
parameter which can be either an integer revno or a
665
self._need_readlock()
666
i = Inventory.read_xml(self.inventory_store[inventory_id])
670
def get_revision_inventory(self, revision_id):
671
"""Return inventory of a past revision."""
672
self._need_readlock()
673
if revision_id == None:
676
return self.get_inventory(self.get_revision(revision_id).inventory_id)
260
679
def revision_history(self):
261
"""Return sequence of revision hashes on to this branch."""
262
raise NotImplementedError('revision_history is abstract')
680
"""Return sequence of revision hashes on to this branch.
682
>>> ScratchBranch().revision_history()
685
self._need_readlock()
686
return [l.rstrip('\r\n') for l in self.controlfile('revision-history', 'r').readlines()]
265
690
"""Return current revision number for this branch.
267
692
That is equivalent to the number of revisions committed to
695
>>> b = ScratchBranch()
698
>>> b.commit('no foo')
270
702
return len(self.revision_history())
273
"""Older format branches cannot bind or unbind."""
274
raise errors.UpgradeRequired(self.base)
276
def last_revision(self):
277
"""Return last patch hash, or None if no history."""
705
def last_patch(self):
706
"""Return last patch hash, or None if no history.
708
>>> ScratchBranch().last_patch() == None
278
711
ph = self.revision_history()
284
def missing_revisions(self, other, stop_revision=None):
285
"""Return a list of new revisions that would perfectly fit.
287
If self and other have not diverged, return a list of the revisions
288
present in other, but missing from self.
290
>>> from bzrlib.workingtree import WorkingTree
291
>>> bzrlib.trace.silent = True
292
>>> d1 = bzrdir.ScratchDir()
293
>>> br1 = d1.open_branch()
294
>>> wt1 = d1.open_workingtree()
295
>>> d2 = bzrdir.ScratchDir()
296
>>> br2 = d2.open_branch()
297
>>> wt2 = d2.open_workingtree()
298
>>> br1.missing_revisions(br2)
300
>>> wt2.commit("lala!", rev_id="REVISION-ID-1")
301
>>> br1.missing_revisions(br2)
303
>>> br2.missing_revisions(br1)
305
>>> wt1.commit("lala!", rev_id="REVISION-ID-1")
306
>>> br1.missing_revisions(br2)
308
>>> wt2.commit("lala!", rev_id="REVISION-ID-2A")
309
>>> br1.missing_revisions(br2)
311
>>> wt1.commit("lala!", rev_id="REVISION-ID-2B")
312
>>> br1.missing_revisions(br2)
313
Traceback (most recent call last):
314
DivergedBranches: These branches have diverged. Try merge.
316
self_history = self.revision_history()
317
self_len = len(self_history)
318
other_history = other.revision_history()
319
other_len = len(other_history)
320
common_index = min(self_len, other_len) -1
321
if common_index >= 0 and \
322
self_history[common_index] != other_history[common_index]:
323
raise DivergedBranches(self, other)
325
if stop_revision is None:
326
stop_revision = other_len
328
assert isinstance(stop_revision, int)
329
if stop_revision > other_len:
330
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
331
return other_history[self_len:stop_revision]
333
def update_revisions(self, other, stop_revision=None):
334
"""Pull in new perfect-fit revisions.
336
:param other: Another Branch to pull from
337
:param stop_revision: Updated until the given revision
340
raise NotImplementedError('update_revisions is abstract')
342
def revision_id_to_revno(self, revision_id):
343
"""Given a revision id, return its revno"""
344
if revision_id is None:
346
history = self.revision_history()
348
return history.index(revision_id) + 1
350
raise bzrlib.errors.NoSuchRevision(self, revision_id)
352
def get_rev_id(self, revno, history=None):
353
"""Find the revision id of the specified revno."""
718
def lookup_revision(self, revno):
719
"""Return revision hash for revision number."""
357
history = self.revision_history()
358
elif revno <= 0 or revno > len(history):
359
raise bzrlib.errors.NoSuchRevision(self, revno)
360
return history[revno - 1]
362
def pull(self, source, overwrite=False, stop_revision=None):
363
raise NotImplementedError('pull is abstract')
724
# list is 0-based; revisions are 1-based
725
return self.revision_history()[revno-1]
727
raise BzrError("no such revision %s" % revno)
730
def revision_tree(self, revision_id):
731
"""Return Tree for a revision on this branch.
733
`revision_id` may be None for the null revision, in which case
734
an `EmptyTree` is returned."""
735
self._need_readlock()
736
if revision_id == None:
739
inv = self.get_revision_inventory(revision_id)
740
return RevisionTree(self.text_store, inv)
743
def working_tree(self):
744
"""Return a `Tree` for the working copy."""
745
return WorkingTree(self.base, self.read_working_inventory())
365
748
def basis_tree(self):
366
749
"""Return `Tree` object for last revision.
368
751
If there are no revisions yet, return an `EmptyTree`.
753
>>> b = ScratchBranch(files=['foo'])
754
>>> b.basis_tree().has_filename('foo')
756
>>> b.working_tree().has_filename('foo')
759
>>> b.commit('add foo')
760
>>> b.basis_tree().has_filename('foo')
370
return self.repository.revision_tree(self.last_revision())
763
r = self.last_patch()
767
return RevisionTree(self.text_store, self.get_revision_inventory(r))
771
def write_log(self, show_timezone='original', verbose=False):
772
"""Write out human-readable log of commits to this branch
774
utc -- If true, show dates in universal time, not local time."""
775
self._need_readlock()
776
## TODO: Option to choose either original, utc or local timezone
779
for p in self.revision_history():
781
print 'revno:', revno
782
## TODO: Show hash if --id is given.
783
##print 'revision-hash:', p
784
rev = self.get_revision(p)
785
print 'committer:', rev.committer
786
print 'timestamp: %s' % (format_date(rev.timestamp, rev.timezone or 0,
789
## opportunistic consistency check, same as check_patch_chaining
790
if rev.precursor != precursor:
791
bailout("mismatched precursor!")
795
print ' (no message)'
797
for l in rev.message.split('\n'):
800
if verbose == True and precursor != None:
801
print 'changed files:'
802
tree = self.revision_tree(p)
803
prevtree = self.revision_tree(precursor)
805
for file_state, fid, old_name, new_name, kind in \
806
diff_trees(prevtree, tree, ):
807
if file_state == 'A' or file_state == 'M':
808
show_status(file_state, kind, new_name)
809
elif file_state == 'D':
810
show_status(file_state, kind, old_name)
811
elif file_state == 'R':
812
show_status(file_state, kind,
813
old_name + ' => ' + new_name)
372
819
def rename_one(self, from_rel, to_rel):
373
820
"""Rename one file.
375
822
This can change the directory or the filename or both.
377
raise NotImplementedError('rename_one is abstract')
824
self._need_writelock()
825
tree = self.working_tree()
827
if not tree.has_filename(from_rel):
828
bailout("can't rename: old working file %r does not exist" % from_rel)
829
if tree.has_filename(to_rel):
830
bailout("can't rename: new working file %r already exists" % to_rel)
832
file_id = inv.path2id(from_rel)
834
bailout("can't rename: old name %r is not versioned" % from_rel)
836
if inv.path2id(to_rel):
837
bailout("can't rename: new name %r is already versioned" % to_rel)
839
to_dir, to_tail = os.path.split(to_rel)
840
to_dir_id = inv.path2id(to_dir)
841
if to_dir_id == None and to_dir != '':
842
bailout("can't determine destination directory id for %r" % to_dir)
844
mutter("rename_one:")
845
mutter(" file_id {%s}" % file_id)
846
mutter(" from_rel %r" % from_rel)
847
mutter(" to_rel %r" % to_rel)
848
mutter(" to_dir %r" % to_dir)
849
mutter(" to_dir_id {%s}" % to_dir_id)
851
inv.rename(file_id, to_dir_id, to_tail)
853
print "%s => %s" % (from_rel, to_rel)
855
from_abs = self.abspath(from_rel)
856
to_abs = self.abspath(to_rel)
858
os.rename(from_abs, to_abs)
860
bailout("failed to rename %r to %r: %s"
861
% (from_abs, to_abs, e[1]),
862
["rename rolled back"])
864
self._write_inventory(inv)
379
868
def move(self, from_paths, to_name):
387
876
Note that to_name is only the last component of the new name;
388
877
this doesn't change the directory.
390
This returns a list of (from_path, to_path) pairs for each
393
raise NotImplementedError('move is abstract')
395
def get_parent(self):
396
"""Return the parent location of the branch.
398
This is the default location for push/pull/missing. The usual
399
pattern is that the user can override it by specifying a
402
raise NotImplementedError('get_parent is abstract')
404
def get_push_location(self):
405
"""Return the None or the location to push this branch to."""
406
raise NotImplementedError('get_push_location is abstract')
408
def set_push_location(self, location):
409
"""Set a new push location for this branch."""
410
raise NotImplementedError('set_push_location is abstract')
412
def set_parent(self, url):
413
raise NotImplementedError('set_parent is abstract')
417
"""Synchronise this branch with the master branch if any.
419
:return: None or the last_revision pivoted out during the update.
423
def check_revno(self, revno):
425
Check whether a revno corresponds to any revision.
426
Zero (the NULL revision) is considered valid.
429
self.check_real_revno(revno)
879
self._need_writelock()
880
## TODO: Option to move IDs only
881
assert not isinstance(from_paths, basestring)
882
tree = self.working_tree()
884
to_abs = self.abspath(to_name)
885
if not isdir(to_abs):
886
bailout("destination %r is not a directory" % to_abs)
887
if not tree.has_filename(to_name):
888
bailout("destination %r not in working directory" % to_abs)
889
to_dir_id = inv.path2id(to_name)
890
if to_dir_id == None and to_name != '':
891
bailout("destination %r is not a versioned directory" % to_name)
892
to_dir_ie = inv[to_dir_id]
893
if to_dir_ie.kind not in ('directory', 'root_directory'):
894
bailout("destination %r is not a directory" % to_abs)
896
to_idpath = Set(inv.get_idpath(to_dir_id))
899
if not tree.has_filename(f):
900
bailout("%r does not exist in working tree" % f)
901
f_id = inv.path2id(f)
903
bailout("%r is not versioned" % f)
904
name_tail = splitpath(f)[-1]
905
dest_path = appendpath(to_name, name_tail)
906
if tree.has_filename(dest_path):
907
bailout("destination %r already exists" % dest_path)
908
if f_id in to_idpath:
909
bailout("can't move %r to a subdirectory of itself" % f)
911
# OK, so there's a race here, it's possible that someone will
912
# create a file in this interval and then the rename might be
913
# left half-done. But we should have caught most problems.
916
name_tail = splitpath(f)[-1]
917
dest_path = appendpath(to_name, name_tail)
918
print "%s => %s" % (f, dest_path)
919
inv.rename(inv.path2id(f), to_dir_id, name_tail)
921
os.rename(self.abspath(f), self.abspath(dest_path))
923
bailout("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
924
["rename rolled back"])
926
self._write_inventory(inv)
930
def show_status(self, show_all=False):
931
"""Display single-line status for non-ignored working files.
933
The list is show sorted in order by file name.
935
>>> b = ScratchBranch(files=['foo', 'foo~'])
941
>>> b.commit("add foo")
943
>>> os.unlink(b.abspath('foo'))
947
TODO: Get state for single files.
949
self._need_readlock()
951
# We have to build everything into a list first so that it can
952
# sorted by name, incorporating all the different sources.
954
# FIXME: Rather than getting things in random order and then sorting,
955
# just step through in order.
957
# Interesting case: the old ID for a file has been removed,
958
# but a new file has been created under that name.
960
old = self.basis_tree()
961
new = self.working_tree()
963
for fs, fid, oldname, newname, kind in diff_trees(old, new):
965
show_status(fs, kind,
966
oldname + ' => ' + newname)
967
elif fs == 'A' or fs == 'M':
968
show_status(fs, kind, newname)
970
show_status(fs, kind, oldname)
973
show_status(fs, kind, newname)
976
show_status(fs, kind, newname)
978
show_status(fs, kind, newname)
980
bailout("weird file state %r" % ((fs, fid),))
984
class ScratchBranch(Branch):
985
"""Special test class: a branch that cleans up after itself.
987
>>> b = ScratchBranch()
995
def __init__(self, files=[], dirs=[]):
996
"""Make a test branch.
998
This creates a temporary directory and runs init-tree in it.
1000
If any files are listed, they are created in the working copy.
1002
Branch.__init__(self, tempfile.mkdtemp(), init=True)
1004
os.mkdir(self.abspath(d))
431
def check_real_revno(self, revno):
433
Check whether a revno corresponds to a real revision.
434
Zero (the NULL revision) is considered invalid
436
if revno < 1 or revno > self.revno():
437
raise InvalidRevisionNumber(revno)
440
def clone(self, *args, **kwargs):
441
"""Clone this branch into to_bzrdir preserving all semantic values.
443
revision_id: if not None, the revision history in the new branch will
444
be truncated to end with revision_id.
446
# for API compatability, until 0.8 releases we provide the old api:
447
# def clone(self, to_location, revision=None, basis_branch=None, to_branch_format=None):
448
# after 0.8 releases, the *args and **kwargs should be changed:
449
# def clone(self, to_bzrdir, revision_id=None):
450
if (kwargs.get('to_location', None) or
451
kwargs.get('revision', None) or
452
kwargs.get('basis_branch', None) or
453
(len(args) and isinstance(args[0], basestring))):
454
# backwards compatability api:
455
warn("Branch.clone() has been deprecated for BzrDir.clone() from"
456
" bzrlib 0.8.", DeprecationWarning, stacklevel=3)
459
basis_branch = args[2]
461
basis_branch = kwargs.get('basis_branch', None)
463
basis = basis_branch.bzrdir
468
revision_id = args[1]
470
revision_id = kwargs.get('revision', None)
475
# no default to raise if not provided.
476
url = kwargs.get('to_location')
477
return self.bzrdir.clone(url,
478
revision_id=revision_id,
479
basis=basis).open_branch()
481
# generate args by hand
483
revision_id = args[1]
485
revision_id = kwargs.get('revision_id', None)
489
# no default to raise if not provided.
490
to_bzrdir = kwargs.get('to_bzrdir')
491
result = self._format.initialize(to_bzrdir)
492
self.copy_content_into(result, revision_id=revision_id)
496
def sprout(self, to_bzrdir, revision_id=None):
497
"""Create a new line of development from the branch, into to_bzrdir.
499
revision_id: if not None, the revision history in the new branch will
500
be truncated to end with revision_id.
502
result = self._format.initialize(to_bzrdir)
503
self.copy_content_into(result, revision_id=revision_id)
504
result.set_parent(self.bzrdir.root_transport.base)
508
def copy_content_into(self, destination, revision_id=None):
509
"""Copy the content of self into destination.
511
revision_id: if not None, the revision history in the new branch will
512
be truncated to end with revision_id.
514
new_history = self.revision_history()
515
if revision_id is not None:
517
new_history = new_history[:new_history.index(revision_id) + 1]
519
rev = self.repository.get_revision(revision_id)
520
new_history = rev.get_history(self.repository)[1:]
521
destination.set_revision_history(new_history)
522
parent = self.get_parent()
524
destination.set_parent(parent)
527
class BranchFormat(object):
528
"""An encapsulation of the initialization and open routines for a format.
530
Formats provide three things:
531
* An initialization routine,
535
Formats are placed in an dict by their format string for reference
536
during branch opening. Its not required that these be instances, they
537
can be classes themselves with class methods - it simply depends on
538
whether state is needed for a given format or not.
540
Once a format is deprecated, just deprecate the initialize and open
541
methods on the format class. Do not deprecate the object, as the
542
object will be created every time regardless.
545
_default_format = None
546
"""The default format used for new branches."""
549
"""The known formats."""
552
def find_format(klass, a_bzrdir):
553
"""Return the format for the branch object in a_bzrdir."""
555
transport = a_bzrdir.get_branch_transport(None)
556
format_string = transport.get("format").read()
557
return klass._formats[format_string]
559
raise NotBranchError(path=transport.base)
561
raise errors.UnknownFormatError(format_string)
564
def get_default_format(klass):
565
"""Return the current default format."""
566
return klass._default_format
568
def get_format_string(self):
569
"""Return the ASCII format string that identifies this format."""
570
raise NotImplementedError(self.get_format_string)
572
def get_format_description(self):
573
"""Return the short format description for this format."""
574
raise NotImplementedError(self.get_format_string)
576
def initialize(self, a_bzrdir):
577
"""Create a branch of this format in a_bzrdir."""
578
raise NotImplementedError(self.initialized)
580
def is_supported(self):
581
"""Is this format supported?
583
Supported formats can be initialized and opened.
584
Unsupported formats may not support initialization or committing or
585
some other features depending on the reason for not being supported.
589
def open(self, a_bzrdir, _found=False):
590
"""Return the branch object for a_bzrdir
592
_found is a private parameter, do not use it. It is used to indicate
593
if format probing has already be done.
595
raise NotImplementedError(self.open)
598
def register_format(klass, format):
599
klass._formats[format.get_format_string()] = format
602
def set_default_format(klass, format):
603
klass._default_format = format
606
def unregister_format(klass, format):
607
assert klass._formats[format.get_format_string()] is format
608
del klass._formats[format.get_format_string()]
611
return self.get_format_string().rstrip()
614
class BzrBranchFormat4(BranchFormat):
615
"""Bzr branch format 4.
618
- a revision-history file.
619
- a branch-lock lock file [ to be shared with the bzrdir ]
622
def get_format_description(self):
623
"""See BranchFormat.get_format_description()."""
624
return "Branch format 4"
626
def initialize(self, a_bzrdir):
627
"""Create a branch of this format in a_bzrdir."""
628
mutter('creating branch in %s', a_bzrdir.transport.base)
629
branch_transport = a_bzrdir.get_branch_transport(self)
630
utf8_files = [('revision-history', ''),
633
control_files = LockableFiles(branch_transport, 'branch-lock',
635
control_files.create_lock()
636
control_files.lock_write()
638
for file, content in utf8_files:
639
control_files.put_utf8(file, content)
641
control_files.unlock()
642
return self.open(a_bzrdir, _found=True)
645
super(BzrBranchFormat4, self).__init__()
646
self._matchingbzrdir = bzrdir.BzrDirFormat6()
648
def open(self, a_bzrdir, _found=False):
649
"""Return the branch object for a_bzrdir
651
_found is a private parameter, do not use it. It is used to indicate
652
if format probing has already be done.
655
# we are being called directly and must probe.
656
raise NotImplementedError
657
return BzrBranch(_format=self,
658
_control_files=a_bzrdir._control_files,
660
_repository=a_bzrdir.open_repository())
663
return "Bazaar-NG branch format 4"
666
class BzrBranchFormat5(BranchFormat):
667
"""Bzr branch format 5.
670
- a revision-history file.
672
- a lock dir guarding the branch itself
673
- all of this stored in a branch/ subdirectory
674
- works with shared repositories.
676
This format is new in bzr 0.8.
679
def get_format_string(self):
680
"""See BranchFormat.get_format_string()."""
681
return "Bazaar-NG branch format 5\n"
683
def get_format_description(self):
684
"""See BranchFormat.get_format_description()."""
685
return "Branch format 5"
687
def initialize(self, a_bzrdir):
688
"""Create a branch of this format in a_bzrdir."""
689
mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
690
branch_transport = a_bzrdir.get_branch_transport(self)
691
utf8_files = [('revision-history', ''),
694
control_files = LockableFiles(branch_transport, 'lock', LockDir)
695
control_files.create_lock()
696
control_files.lock_write()
697
control_files.put_utf8('format', self.get_format_string())
699
for file, content in utf8_files:
700
control_files.put_utf8(file, content)
702
control_files.unlock()
703
return self.open(a_bzrdir, _found=True, )
706
super(BzrBranchFormat5, self).__init__()
707
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
709
def open(self, a_bzrdir, _found=False):
710
"""Return the branch object for a_bzrdir
712
_found is a private parameter, do not use it. It is used to indicate
713
if format probing has already be done.
716
format = BranchFormat.find_format(a_bzrdir)
717
assert format.__class__ == self.__class__
718
transport = a_bzrdir.get_branch_transport(None)
719
control_files = LockableFiles(transport, 'lock', LockDir)
720
return BzrBranch5(_format=self,
721
_control_files=control_files,
723
_repository=a_bzrdir.find_repository())
726
return "Bazaar-NG Metadir branch format 5"
729
class BranchReferenceFormat(BranchFormat):
730
"""Bzr branch reference format.
732
Branch references are used in implementing checkouts, they
733
act as an alias to the real branch which is at some other url.
740
def get_format_string(self):
741
"""See BranchFormat.get_format_string()."""
742
return "Bazaar-NG Branch Reference Format 1\n"
744
def get_format_description(self):
745
"""See BranchFormat.get_format_description()."""
746
return "Checkout reference format 1"
748
def initialize(self, a_bzrdir, target_branch=None):
749
"""Create a branch of this format in a_bzrdir."""
750
if target_branch is None:
751
# this format does not implement branch itself, thus the implicit
752
# creation contract must see it as uninitializable
753
raise errors.UninitializableFormat(self)
754
mutter('creating branch reference in %s', a_bzrdir.transport.base)
755
branch_transport = a_bzrdir.get_branch_transport(self)
756
# FIXME rbc 20060209 one j-a-ms encoding branch lands this str() cast is not needed.
757
branch_transport.put('location', StringIO(str(target_branch.bzrdir.root_transport.base)))
758
branch_transport.put('format', StringIO(self.get_format_string()))
759
return self.open(a_bzrdir, _found=True)
762
super(BranchReferenceFormat, self).__init__()
763
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
765
def _make_reference_clone_function(format, a_branch):
766
"""Create a clone() routine for a branch dynamically."""
767
def clone(to_bzrdir, revision_id=None):
768
"""See Branch.clone()."""
769
return format.initialize(to_bzrdir, a_branch)
770
# cannot obey revision_id limits when cloning a reference ...
771
# FIXME RBC 20060210 either nuke revision_id for clone, or
772
# emit some sort of warning/error to the caller ?!
775
def open(self, a_bzrdir, _found=False):
776
"""Return the branch that the branch reference in a_bzrdir points at.
778
_found is a private parameter, do not use it. It is used to indicate
779
if format probing has already be done.
782
format = BranchFormat.find_format(a_bzrdir)
783
assert format.__class__ == self.__class__
784
transport = a_bzrdir.get_branch_transport(None)
785
real_bzrdir = bzrdir.BzrDir.open(transport.get('location').read())
786
result = real_bzrdir.open_branch()
787
# this changes the behaviour of result.clone to create a new reference
788
# rather than a copy of the content of the branch.
789
# I did not use a proxy object because that needs much more extensive
790
# testing, and we are only changing one behaviour at the moment.
791
# If we decide to alter more behaviours - i.e. the implicit nickname
792
# then this should be refactored to introduce a tested proxy branch
793
# and a subclass of that for use in overriding clone() and ....
795
result.clone = self._make_reference_clone_function(result)
799
# formats which have no format string are not discoverable
800
# and not independently creatable, so are not registered.
801
__default_format = BzrBranchFormat5()
802
BranchFormat.register_format(__default_format)
803
BranchFormat.register_format(BranchReferenceFormat())
804
BranchFormat.set_default_format(__default_format)
805
_legacy_formats = [BzrBranchFormat4(),
808
class BzrBranch(Branch):
809
"""A branch stored in the actual filesystem.
811
Note that it's "local" in the context of the filesystem; it doesn't
812
really matter if it's on an nfs/smb/afs/coda/... share, as long as
813
it's writable, and can be accessed via the normal filesystem API.
816
def __init__(self, transport=DEPRECATED_PARAMETER, init=DEPRECATED_PARAMETER,
817
relax_version_check=DEPRECATED_PARAMETER, _format=None,
818
_control_files=None, a_bzrdir=None, _repository=None):
819
"""Create new branch object at a particular location.
821
transport -- A Transport object, defining how to access files.
823
init -- If True, create new control files in a previously
824
unversioned directory. If False, the branch must already
827
relax_version_check -- If true, the usual check for the branch
828
version is not applied. This is intended only for
829
upgrade/recovery type use; it's not guaranteed that
830
all operations will work on old format branches.
833
self.bzrdir = bzrdir.BzrDir.open(transport.base)
835
self.bzrdir = a_bzrdir
836
self._transport = self.bzrdir.transport.clone('..')
837
self._base = self._transport.base
838
self._format = _format
839
if _control_files is None:
840
raise BzrBadParameterMissing('_control_files')
841
self.control_files = _control_files
842
if deprecated_passed(init):
843
warn("BzrBranch.__init__(..., init=XXX): The init parameter is "
844
"deprecated as of bzr 0.8. Please use Branch.create().",
848
# this is slower than before deprecation, oh well never mind.
850
self._initialize(transport.base)
851
self._check_format(_format)
852
if deprecated_passed(relax_version_check):
853
warn("BzrBranch.__init__(..., relax_version_check=XXX_: The "
854
"relax_version_check parameter is deprecated as of bzr 0.8. "
855
"Please use BzrDir.open_downlevel, or a BzrBranchFormat's "
859
if (not relax_version_check
860
and not self._format.is_supported()):
861
raise errors.UnsupportedFormatError(
862
'sorry, branch format %r not supported' % fmt,
863
['use a different bzr version',
864
'or remove the .bzr directory'
865
' and "bzr init" again'])
866
if deprecated_passed(transport):
867
warn("BzrBranch.__init__(transport=XXX...): The transport "
868
"parameter is deprecated as of bzr 0.8. "
869
"Please use Branch.open, or bzrdir.open_branch().",
872
self.repository = _repository
875
return '%s(%r)' % (self.__class__.__name__, self.base)
1007
file(os.path.join(self.base, f), 'w').write('content of %s' % f)
879
1010
def __del__(self):
880
# TODO: It might be best to do this somewhere else,
881
# but it is nice for a Branch object to automatically
882
# cache it's information.
883
# Alternatively, we could have the Transport objects cache requests
884
# See the earlier discussion about how major objects (like Branch)
885
# should never expect their __del__ function to run.
886
# XXX: cache_root seems to be unused, 2006-01-13 mbp
887
if hasattr(self, 'cache_root') and self.cache_root is not None:
889
shutil.rmtree(self.cache_root)
892
self.cache_root = None
897
base = property(_get_base, doc="The URL for the root of this branch.")
899
def _finish_transaction(self):
900
"""Exit the current transaction."""
901
return self.control_files._finish_transaction()
903
def get_transaction(self):
904
"""Return the current active transaction.
906
If no transaction is active, this returns a passthrough object
907
for which all data is immediately flushed and no caching happens.
909
# this is an explicit function so that we can do tricky stuff
910
# when the storage in rev_storage is elsewhere.
911
# we probably need to hook the two 'lock a location' and
912
# 'have a transaction' together more delicately, so that
913
# we can have two locks (branch and storage) and one transaction
914
# ... and finishing the transaction unlocks both, but unlocking
915
# does not. - RBC 20051121
916
return self.control_files.get_transaction()
918
def _set_transaction(self, transaction):
919
"""Set a new active transaction."""
920
return self.control_files._set_transaction(transaction)
922
def abspath(self, name):
923
"""See Branch.abspath."""
924
return self.control_files._transport.abspath(name)
926
def _check_format(self, format):
927
"""Identify the branch format if needed.
929
The format is stored as a reference to the format object in
930
self._format for code that needs to check it later.
932
The format parameter is either None or the branch format class
933
used to open this branch.
935
FIXME: DELETE THIS METHOD when pre 0.8 support is removed.
938
format = BzrBranchFormat.find_format(self.bzrdir)
939
self._format = format
940
mutter("got branch format %s", self._format)
943
def get_root_id(self):
944
"""See Branch.get_root_id."""
945
tree = self.repository.revision_tree(self.last_revision())
946
return tree.inventory.root.file_id
949
return self.control_files.is_locked()
951
def lock_write(self):
952
# TODO: test for failed two phase locks. This is known broken.
953
self.control_files.lock_write()
954
self.repository.lock_write()
957
# TODO: test for failed two phase locks. This is known broken.
958
self.control_files.lock_read()
959
self.repository.lock_read()
962
# TODO: test for failed two phase locks. This is known broken.
963
self.repository.unlock()
964
self.control_files.unlock()
966
def peek_lock_mode(self):
967
if self.control_files._lock_count == 0:
970
return self.control_files._lock_mode
972
def get_physical_lock_status(self):
973
return self.control_files.get_physical_lock_status()
976
def print_file(self, file, revision_id):
977
"""See Branch.print_file."""
978
return self.repository.print_file(file, revision_id)
981
def append_revision(self, *revision_ids):
982
"""See Branch.append_revision."""
983
for revision_id in revision_ids:
984
mutter("add {%s} to revision-history" % revision_id)
985
rev_history = self.revision_history()
986
rev_history.extend(revision_ids)
987
self.set_revision_history(rev_history)
990
def set_revision_history(self, rev_history):
991
"""See Branch.set_revision_history."""
992
self.control_files.put_utf8(
993
'revision-history', '\n'.join(rev_history))
994
transaction = self.get_transaction()
995
history = transaction.map.find_revision_history()
996
if history is not None:
997
# update the revision history in the identity map.
998
history[:] = list(rev_history)
999
# this call is disabled because revision_history is
1000
# not really an object yet, and the transaction is for objects.
1001
# transaction.register_dirty(history)
1003
transaction.map.add_revision_history(rev_history)
1004
# this call is disabled because revision_history is
1005
# not really an object yet, and the transaction is for objects.
1006
# transaction.register_clean(history)
1008
def get_revision_delta(self, revno):
1009
"""Return the delta for one revision.
1011
The delta is relative to its mainline predecessor, or the
1012
empty tree for revision 1.
1014
assert isinstance(revno, int)
1015
rh = self.revision_history()
1016
if not (1 <= revno <= len(rh)):
1017
raise InvalidRevisionNumber(revno)
1019
# revno is 1-based; list is 0-based
1021
new_tree = self.repository.revision_tree(rh[revno-1])
1023
old_tree = EmptyTree()
1025
old_tree = self.repository.revision_tree(rh[revno-2])
1026
return compare_trees(old_tree, new_tree)
1029
def revision_history(self):
1030
"""See Branch.revision_history."""
1031
transaction = self.get_transaction()
1032
history = transaction.map.find_revision_history()
1033
if history is not None:
1034
mutter("cache hit for revision-history in %s", self)
1035
return list(history)
1036
history = [l.rstrip('\r\n') for l in
1037
self.control_files.get_utf8('revision-history').readlines()]
1038
transaction.map.add_revision_history(history)
1039
# this call is disabled because revision_history is
1040
# not really an object yet, and the transaction is for objects.
1041
# transaction.register_clean(history, precious=True)
1042
return list(history)
1045
def update_revisions(self, other, stop_revision=None):
1046
"""See Branch.update_revisions."""
1049
if stop_revision is None:
1050
stop_revision = other.last_revision()
1051
if stop_revision is None:
1052
# if there are no commits, we're done.
1054
# whats the current last revision, before we fetch [and change it
1056
last_rev = self.last_revision()
1057
# we fetch here regardless of whether we need to so that we pickup
1059
self.fetch(other, stop_revision)
1060
my_ancestry = self.repository.get_ancestry(last_rev)
1061
if stop_revision in my_ancestry:
1062
# last_revision is a descendant of stop_revision
1064
# stop_revision must be a descendant of last_revision
1065
stop_graph = self.repository.get_revision_graph(stop_revision)
1066
if last_rev is not None and last_rev not in stop_graph:
1067
# our previous tip is not merged into stop_revision
1068
raise errors.DivergedBranches(self, other)
1069
# make a new revision history from the graph
1070
current_rev_id = stop_revision
1072
while current_rev_id not in (None, NULL_REVISION):
1073
new_history.append(current_rev_id)
1074
current_rev_id_parents = stop_graph[current_rev_id]
1076
current_rev_id = current_rev_id_parents[0]
1078
current_rev_id = None
1079
new_history.reverse()
1080
self.set_revision_history(new_history)
1084
@deprecated_method(zero_eight)
1085
def pullable_revisions(self, other, stop_revision):
1086
"""Please use bzrlib.missing instead."""
1087
other_revno = other.revision_id_to_revno(stop_revision)
1089
return self.missing_revisions(other, other_revno)
1090
except DivergedBranches, e:
1092
pullable_revs = get_intervening_revisions(self.last_revision(),
1095
assert self.last_revision() not in pullable_revs
1096
return pullable_revs
1097
except bzrlib.errors.NotAncestor:
1098
if is_ancestor(self.last_revision(), stop_revision, self):
1103
def basis_tree(self):
1104
"""See Branch.basis_tree."""
1105
return self.repository.revision_tree(self.last_revision())
1107
@deprecated_method(zero_eight)
1108
def working_tree(self):
1109
"""Create a Working tree object for this branch."""
1110
from bzrlib.workingtree import WorkingTree
1111
from bzrlib.transport.local import LocalTransport
1112
if (self.base.find('://') != -1 or
1113
not isinstance(self._transport, LocalTransport)):
1114
raise NoWorkingTree(self.base)
1115
return self.bzrdir.open_workingtree()
1118
def pull(self, source, overwrite=False, stop_revision=None):
1119
"""See Branch.pull."""
1122
old_count = len(self.revision_history())
1124
self.update_revisions(source,stop_revision)
1125
except DivergedBranches:
1129
self.set_revision_history(source.revision_history())
1130
new_count = len(self.revision_history())
1131
return new_count - old_count
1135
def get_parent(self):
1136
"""See Branch.get_parent."""
1138
_locs = ['parent', 'pull', 'x-pull']
1141
return self.control_files.get_utf8(l).read().strip('\n')
1146
def get_push_location(self):
1147
"""See Branch.get_push_location."""
1148
config = bzrlib.config.BranchConfig(self)
1149
push_loc = config.get_user_option('push_location')
1152
def set_push_location(self, location):
1153
"""See Branch.set_push_location."""
1154
config = bzrlib.config.LocationConfig(self.base)
1155
config.set_user_option('push_location', location)
1158
def set_parent(self, url):
1159
"""See Branch.set_parent."""
1160
# TODO: Maybe delete old location files?
1161
# URLs should never be unicode, even on the local fs,
1162
# FIXUP this and get_parent in a future branch format bump:
1163
# read and rewrite the file, and have the new format code read
1164
# using .get not .get_utf8. RBC 20060125
1166
self.control_files._transport.delete('parent')
1168
self.control_files.put_utf8('parent', url + '\n')
1170
def tree_config(self):
1171
return TreeConfig(self)
1174
class BzrBranch5(BzrBranch):
1175
"""A format 5 branch. This supports new features over plan branches.
1177
It has support for a master_branch which is the data for bound branches.
1185
super(BzrBranch5, self).__init__(_format=_format,
1186
_control_files=_control_files,
1188
_repository=_repository)
1191
def pull(self, source, overwrite=False, stop_revision=None):
1192
"""Updates branch.pull to be bound branch aware."""
1193
bound_location = self.get_bound_location()
1194
if source.base != bound_location:
1195
# not pulling from master, so we need to update master.
1196
master_branch = self.get_master_branch()
1198
master_branch.pull(source)
1199
source = master_branch
1200
return super(BzrBranch5, self).pull(source, overwrite, stop_revision)
1202
def get_bound_location(self):
1204
return self.control_files.get_utf8('bound').read()[:-1]
1205
except errors.NoSuchFile:
1209
def get_master_branch(self):
1210
"""Return the branch we are bound to.
1212
:return: Either a Branch, or None
1214
This could memoise the branch, but if thats done
1215
it must be revalidated on each new lock.
1216
So for now we just dont memoise it.
1217
# RBC 20060304 review this decision.
1219
bound_loc = self.get_bound_location()
1223
return Branch.open(bound_loc)
1224
except (errors.NotBranchError, errors.ConnectionError), e:
1225
raise errors.BoundBranchConnectionFailure(
1229
def set_bound_location(self, location):
1230
"""Set the target where this branch is bound to.
1232
:param location: URL to the target branch
1235
self.control_files.put_utf8('bound', location+'\n')
1238
self.control_files._transport.delete('bound')
1011
"""Destroy the test branch, removing the scratch directory."""
1013
shutil.rmtree(self.base)
1015
# Work around for shutil.rmtree failing on Windows when
1016
# readonly files are encountered
1017
for root, dirs, files in os.walk(self.base, topdown=False):
1019
os.chmod(os.path.join(root, name), 0700)
1020
shutil.rmtree(self.base)
1024
######################################################################
1028
def is_control_file(filename):
1029
## FIXME: better check
1030
filename = os.path.normpath(filename)
1031
while filename != '':
1032
head, tail = os.path.split(filename)
1033
## mutter('check %r for control file' % ((head, tail), ))
1034
if tail == bzrlib.BZRDIR:
1244
def bind(self, other):
1245
"""Bind the local branch the other branch.
1247
:param other: The branch to bind to
1250
# TODO: jam 20051230 Consider checking if the target is bound
1251
# It is debatable whether you should be able to bind to
1252
# a branch which is itself bound.
1253
# Committing is obviously forbidden,
1254
# but binding itself may not be.
1255
# Since we *have* to check at commit time, we don't
1256
# *need* to check here
1259
# we are now equal to or a suffix of other.
1261
# Since we have 'pulled' from the remote location,
1262
# now we should try to pull in the opposite direction
1263
# in case the local tree has more revisions than the
1265
# There may be a different check you could do here
1266
# rather than actually trying to install revisions remotely.
1267
# TODO: capture an exception which indicates the remote branch
1269
# If it is up-to-date, this probably should not be a failure
1271
# lock other for write so the revision-history syncing cannot race
1275
# if this does not error, other now has the same last rev we do
1276
# it can only error if the pull from other was concurrent with
1277
# a commit to other from someone else.
1279
# until we ditch revision-history, we need to sync them up:
1280
self.set_revision_history(other.revision_history())
1281
# now other and self are up to date with each other and have the
1282
# same revision-history.
1286
self.set_bound_location(other.base)
1290
"""If bound, unbind"""
1291
return self.set_bound_location(None)
1295
"""Synchronise this branch with the master branch if any.
1297
:return: None or the last_revision that was pivoted out during the
1300
master = self.get_master_branch()
1301
if master is not None:
1302
old_tip = self.last_revision()
1303
self.pull(master, overwrite=True)
1304
if old_tip in self.repository.get_ancestry(self.last_revision()):
1310
class BranchTestProviderAdapter(object):
1311
"""A tool to generate a suite testing multiple branch formats at once.
1313
This is done by copying the test once for each transport and injecting
1314
the transport_server, transport_readonly_server, and branch_format
1315
classes into each copy. Each copy is also given a new id() to make it
1319
def __init__(self, transport_server, transport_readonly_server, formats):
1320
self._transport_server = transport_server
1321
self._transport_readonly_server = transport_readonly_server
1322
self._formats = formats
1324
def adapt(self, test):
1325
result = TestSuite()
1326
for branch_format, bzrdir_format in self._formats:
1327
new_test = deepcopy(test)
1328
new_test.transport_server = self._transport_server
1329
new_test.transport_readonly_server = self._transport_readonly_server
1330
new_test.bzrdir_format = bzrdir_format
1331
new_test.branch_format = branch_format
1332
def make_new_test_id():
1333
new_id = "%s(%s)" % (new_test.id(), branch_format.__class__.__name__)
1334
return lambda: new_id
1335
new_test.id = make_new_test_id()
1336
result.addTest(new_test)
1340
######################################################################
1344
@deprecated_function(zero_eight)
1345
def ScratchBranch(*args, **kwargs):
1346
"""See bzrlib.bzrdir.ScratchDir."""
1347
d = ScratchDir(*args, **kwargs)
1348
return d.open_branch()
1351
@deprecated_function(zero_eight)
1352
def is_control_file(*args, **kwargs):
1353
"""See bzrlib.workingtree.is_control_file."""
1354
return bzrlib.workingtree.is_control_file(*args, **kwargs)
1036
if filename == head:
1043
def _gen_revision_id(when):
1044
"""Return new revision-id."""
1045
s = '%s-%s-' % (user_email(), compact_date(when))
1046
s += hexlify(rand_bytes(8))
1050
def gen_file_id(name):
1051
"""Return new file id.
1053
This should probably generate proper UUIDs, but for the moment we
1054
cope with just randomness because running uuidgen every time is
1056
idx = name.rfind('/')
1058
name = name[idx+1 : ]
1059
idx = name.rfind('\\')
1061
name = name[idx+1 : ]
1063
name = name.lstrip('.')
1065
s = hexlify(rand_bytes(8))
1066
return '-'.join((name, compact_date(time.time()), s))