23
23
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
25
25
sha_file, appendpath, file_kind
26
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId
27
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId, \
28
DivergedBranches, NotBranchError
28
29
from bzrlib.textui import show_status
29
30
from bzrlib.revision import Revision
30
from bzrlib.xml import unpack_xml
31
31
from bzrlib.delta import compare_trees
32
32
from bzrlib.tree import EmptyTree, RevisionTree
34
38
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
35
39
## TODO: Maybe include checks for common corruption of newlines, etc?
39
43
# repeatedly to calculate deltas. We could perhaps have a weakref
40
44
# cache in memory to make this faster.
46
# TODO: please move the revision-string syntax stuff out of the branch
47
# object; it's clutter
43
50
def find_branch(f, **args):
44
if f and (f.startswith('http://') or f.startswith('https://')):
46
return remotebranch.RemoteBranch(f, **args)
48
return Branch(f, **args)
51
def find_cached_branch(f, cache_root, **args):
52
from remotebranch import RemoteBranch
53
br = find_branch(f, **args)
54
def cacheify(br, store_name):
55
from meta_store import CachedStore
56
cache_path = os.path.join(cache_root, store_name)
58
new_store = CachedStore(getattr(br, store_name), cache_path)
59
setattr(br, store_name, new_store)
61
if isinstance(br, RemoteBranch):
62
cacheify(br, 'inventory_store')
63
cacheify(br, 'text_store')
64
cacheify(br, 'revision_store')
51
from bzrlib.transport import transport
52
from bzrlib.local_transport import LocalTransport
54
# FIXME: This is a hack around transport so that
55
# We can search the local directories for
57
if args.has_key('init') and args['init']:
58
# Don't search if we are init-ing
59
return Branch(t, **args)
60
if isinstance(t, LocalTransport):
61
root = find_branch_root(f)
64
return Branch(t, **args)
68
66
def _relpath(base, path):
69
67
"""Return path relative to base, or raise exception.
153
145
_lock_mode = None
154
146
_lock_count = None
157
150
# Map some sort of prefix into a namespace
158
151
# stuff like "revno:10", "revid:", etc.
159
152
# This should match a prefix with a function which accepts
160
153
REVISION_NAMESPACES = {}
162
def __init__(self, base, init=False, find_root=True):
155
def __init__(self, transport, init=False):
163
156
"""Create new branch object at a particular location.
165
base -- Base directory for the branch.
158
transport -- A Transport object, defining how to access files.
159
(If a string, transport.transport() will be used to
160
create a Transport object)
167
162
init -- If True, create new control files in a previously
168
163
unversioned directory. If False, the branch must already
171
find_root -- If true and init is false, find the root of the
172
existing branch containing base.
174
166
In the test suite, creation of new trees is tested using the
175
167
`ScratchBranch` class.
177
from bzrlib.store import ImmutableStore
169
if isinstance(transport, basestring):
170
from transport import transport as get_transport
171
transport = get_transport(transport)
173
self._transport = transport
179
self.base = os.path.realpath(base)
180
175
self._make_control()
182
self.base = find_branch_root(base)
184
self.base = os.path.realpath(base)
185
if not isdir(self.controlfilename('.')):
186
from errors import NotBranchError
187
raise NotBranchError("not a bzr branch: %s" % quotefn(base),
188
['use "bzr init" to initialize a new working tree',
189
'current bzr can only operate from top-of-tree'])
190
176
self._check_format()
192
self.text_store = ImmutableStore(self.controlfilename('text-store'))
193
self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
194
self.inventory_store = ImmutableStore(self.controlfilename('inventory-store'))
197
179
def __str__(self):
198
return '%s(%r)' % (self.__class__.__name__, self.base)
180
return '%s(%r)' % (self.__class__.__name__, self._transport.base)
201
183
__repr__ = __str__
204
186
def __del__(self):
205
187
if self._lock_mode or self._lock:
206
from warnings import warn
188
from bzrlib.warnings import warn
207
189
warn("branch %r was not explicitly unlocked" % self)
208
190
self._lock.unlock()
192
# TODO: It might be best to do this somewhere else,
193
# but it is nice for a Branch object to automatically
194
# cache it's information.
195
# Alternatively, we could have the Transport objects cache requests
196
# See the earlier discussion about how major objects (like Branch)
197
# should never expect their __del__ function to run.
198
if self.cache_root is not None:
199
#from warnings import warn
200
#warn("branch %r auto-cleanup of cache files" % self)
203
shutil.rmtree(self.cache_root)
206
self.cache_root = None
210
return self._transport.base
213
base = property(_get_base)
212
216
def lock_write(self):
217
# TODO: Upgrade locking to support using a Transport,
218
# and potentially a remote locking protocol
213
219
if self._lock_mode:
214
220
if self._lock_mode != 'w':
215
from errors import LockError
221
from bzrlib.errors import LockError
216
222
raise LockError("can't upgrade to a write lock from %r" %
218
224
self._lock_count += 1
220
from bzrlib.lock import WriteLock
222
self._lock = WriteLock(self.controlfilename('branch-lock'))
226
self._lock = self._transport.lock_write(
227
self._rel_controlfilename('branch-lock'))
223
228
self._lock_mode = 'w'
224
229
self._lock_count = 1
228
232
def lock_read(self):
229
233
if self._lock_mode:
230
234
assert self._lock_mode in ('r', 'w'), \
231
235
"invalid lock mode %r" % self._lock_mode
232
236
self._lock_count += 1
234
from bzrlib.lock import ReadLock
236
self._lock = ReadLock(self.controlfilename('branch-lock'))
238
self._lock = self._transport.lock_read(
239
self._rel_controlfilename('branch-lock'))
237
240
self._lock_mode = 'r'
238
241
self._lock_count = 1
242
243
def unlock(self):
243
244
if not self._lock_mode:
244
from errors import LockError
245
from bzrlib.errors import LockError
245
246
raise LockError('branch %r is not locked' % (self))
247
248
if self._lock_count > 1:
251
252
self._lock = None
252
253
self._lock_mode = self._lock_count = None
255
255
def abspath(self, name):
256
256
"""Return absolute filename for something in the branch"""
257
return os.path.join(self.base, name)
257
return self._transport.abspath(name)
260
259
def relpath(self, path):
261
260
"""Return path relative to this branch of something inside it.
263
262
Raises an error if path is not in this branch."""
264
return _relpath(self.base, path)
263
return self._transport.relpath(path)
266
def _rel_controlfilename(self, file_or_path):
267
if isinstance(file_or_path, basestring):
268
file_or_path = [file_or_path]
269
return [bzrlib.BZRDIR] + file_or_path
267
271
def controlfilename(self, file_or_path):
268
272
"""Return location relative to branch."""
269
if isinstance(file_or_path, basestring):
270
file_or_path = [file_or_path]
271
return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
273
return self._transport.abspath(self._rel_controlfilename(file_or_path))
274
276
def controlfile(self, file_or_path, mode='r'):
282
284
Controlfiles should almost never be opened in write mode but
283
285
rather should be atomically copied and replaced using atomicfile.
286
fn = self.controlfilename(file_or_path)
288
if mode == 'rb' or mode == 'wb':
289
return file(fn, mode)
290
elif mode == 'r' or mode == 'w':
291
# open in binary mode anyhow so there's no newline translation;
292
# codecs uses line buffering by default; don't want that.
294
return codecs.open(fn, mode + 'b', 'utf-8',
289
relpath = self._rel_controlfilename(file_or_path)
290
#TODO: codecs.open() buffers linewise, so it was overloaded with
291
# a much larger buffer, do we need to do the same for getreader/getwriter?
293
return self._transport.get(relpath)
295
raise BzrError("Branch.controlfile(mode='wb') is not supported, use put_controlfiles")
297
return codecs.getreader('utf-8')(self._transport.get(relpath), errors='replace')
299
raise BzrError("Branch.controlfile(mode='w') is not supported, use put_controlfiles")
297
301
raise BzrError("invalid controlfile mode %r" % mode)
303
def put_controlfile(self, path, f, encode=True):
304
"""Write an entry as a controlfile.
306
:param path: The path to put the file, relative to the .bzr control
308
:param f: A file-like or string object whose contents should be copied.
309
:param encode: If true, encode the contents as utf-8
311
self.put_controlfiles([(path, f)], encode=encode)
313
def put_controlfiles(self, files, encode=True):
314
"""Write several entries as controlfiles.
316
:param files: A list of [(path, file)] pairs, where the path is the directory
317
underneath the bzr control directory
318
:param encode: If true, encode the contents as utf-8
322
for path, f in files:
324
if isinstance(f, basestring):
325
f = f.encode('utf-8', 'replace')
327
f = codecs.getwriter('utf-8')(f, errors='replace')
328
path = self._rel_controlfilename(path)
329
ctrl_files.append((path, f))
330
self._transport.put_multi(ctrl_files)
301
332
def _make_control(self):
302
333
from bzrlib.inventory import Inventory
303
from bzrlib.xml import pack_xml
334
from cStringIO import StringIO
305
os.mkdir(self.controlfilename([]))
306
self.controlfile('README', 'w').write(
336
# Create an empty inventory
338
# if we want per-tree root ids then this is the place to set
339
# them; they're not needed for now and so ommitted for
341
bzrlib.xml.serializer_v4.write_inventory(Inventory(), sio)
343
dirs = [[], 'text-store', 'inventory-store', 'revision-store']
307
345
"This is a Bazaar-NG control directory.\n"
308
"Do not change any files in this directory.\n")
309
self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT)
310
for d in ('text-store', 'inventory-store', 'revision-store'):
311
os.mkdir(self.controlfilename(d))
312
for f in ('revision-history', 'merged-patches',
313
'pending-merged-patches', 'branch-name',
316
self.controlfile(f, 'w').write('')
317
mutter('created control directory in ' + self.base)
319
pack_xml(Inventory(gen_root_id()), self.controlfile('inventory','w'))
346
"Do not change any files in this directory.\n"),
347
('branch-format', BZR_BRANCH_FORMAT),
348
('revision-history', ''),
349
('merged-patches', ''),
350
('pending-merged-patches', ''),
353
('pending-merges', ''),
354
('inventory', sio.getvalue())
356
self._transport.mkdir_multi([self._rel_controlfilename(d) for d in dirs])
357
self.put_controlfiles(files)
358
mutter('created control directory in ' + self._transport.base)
322
360
def _check_format(self):
323
361
"""Check this branch format is supported.
331
369
# on Windows from Linux and so on. I think it might be better
332
370
# to always make all internal files in unix format.
333
371
fmt = self.controlfile('branch-format', 'r').read()
334
fmt.replace('\r\n', '')
372
fmt = fmt.replace('\r\n', '\n')
335
373
if fmt != BZR_BRANCH_FORMAT:
336
374
raise BzrError('sorry, branch format %r not supported' % fmt,
337
375
['use a different bzr version',
338
376
'or remove the .bzr directory and "bzr init" again'])
378
# We know that the format is the currently supported one.
379
# So create the rest of the entries.
380
from bzrlib.store.compressed_text import CompressedTextStore
382
if self._transport.should_cache():
384
self.cache_root = tempfile.mkdtemp(prefix='bzr-cache')
385
mutter('Branch %r using caching in %r' % (self, self.cache_root))
387
self.cache_root = None
390
relpath = self._rel_controlfilename(name)
391
store = CompressedTextStore(self._transport.clone(relpath))
392
if self._transport.should_cache():
393
from meta_store import CachedStore
394
cache_path = os.path.join(self.cache_root, name)
396
store = CachedStore(store, cache_path)
399
self.text_store = get_store('text-store')
400
self.revision_store = get_store('revision-store')
401
self.inventory_store = get_store('inventory-store')
340
403
def get_root_id(self):
341
404
"""Return the id of this branches root"""
342
405
inv = self.read_working_inventory()
636
683
return compare_trees(old_tree, new_tree)
686
def get_revisions(self, revision_ids, pb=None):
687
"""Return the Revision object for a set of named revisions"""
688
from bzrlib.revision import Revision
689
from bzrlib.xml import unpack_xml
691
# TODO: We need to decide what to do here
692
# we cannot use a generator with a try/finally, because
693
# you cannot guarantee that the caller will iterate through
695
# in the past, get_inventory wasn't even wrapped in a
696
# try/finally locking block.
697
# We could either lock without the try/finally, or just
698
# not lock at all. We are reading entries that should
700
# I prefer locking with no finally, so that if someone
701
# asks for a list of revisions, but doesn't consume them,
702
# that is their problem, and they will suffer the consequences
704
for xml_file in self.revision_store.get(revision_ids, pb=pb):
706
r = bzrlib.xml.serializer_v4.read_revision(xml_file)
707
except SyntaxError, e:
708
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
640
714
def get_revision_sha1(self, revision_id):
641
715
"""Hash the stored value of a revision, and return it."""
642
716
# In the future, revision entries will be signed. At that
654
728
TODO: Perhaps for this and similar methods, take a revision
655
729
parameter which can be either an integer revno or a
732
f = self.get_inventory_xml_file(inventory_id)
733
return bzrlib.xml.serializer_v4.read_inventory(f)
736
def get_inventory_xml(self, inventory_id):
737
"""Get inventory XML as a file object."""
738
# Shouldn't this have a read-lock around it?
739
# As well as some sort of trap for missing ids?
740
return self.inventory_store[inventory_id]
742
get_inventory_xml_file = get_inventory_xml
744
def get_inventories(self, inventory_ids, pb=None, ignore_missing=False):
745
"""Get Inventory objects by id
657
747
from bzrlib.inventory import Inventory
658
from bzrlib.xml import unpack_xml
660
return unpack_xml(Inventory, self.inventory_store[inventory_id])
749
# See the discussion in get_revisions for why
750
# we don't use a try/finally block here
752
for f in self.inventory_store.get(inventory_ids, pb=pb, ignore_missing=ignore_missing):
754
# TODO: Possibly put a try/except around this to handle
755
# read serialization errors
756
r = bzrlib.xml.serializer_v4.read_inventory(f)
761
raise bzrlib.errors.NoSuchRevision(self, revision_id)
663
764
def get_inventory_sha1(self, inventory_id):
664
765
"""Return the sha1 hash of the inventory entry
666
return sha_file(self.inventory_store[inventory_id])
767
return sha_file(self.get_inventory_xml(inventory_id))
669
770
def get_revision_inventory(self, revision_id):
694
795
def common_ancestor(self, other, self_revno=None, other_revno=None):
797
>>> from bzrlib.commit import commit
697
798
>>> sb = ScratchBranch(files=['foo', 'foo~'])
698
799
>>> sb.common_ancestor(sb) == (None, None)
700
>>> commit.commit(sb, "Committing first revision", verbose=False)
801
>>> commit(sb, "Committing first revision", verbose=False)
701
802
>>> sb.common_ancestor(sb)[0]
703
804
>>> clone = sb.clone()
704
>>> commit.commit(sb, "Committing second revision", verbose=False)
805
>>> commit(sb, "Committing second revision", verbose=False)
705
806
>>> sb.common_ancestor(sb)[0]
707
808
>>> sb.common_ancestor(clone)[0]
709
>>> commit.commit(clone, "Committing divergent second revision",
810
>>> commit(clone, "Committing divergent second revision",
710
811
... verbose=False)
711
812
>>> sb.common_ancestor(clone)[0]
794
895
if stop_revision is None:
795
896
stop_revision = other_len
796
897
elif stop_revision > other_len:
797
raise NoSuchRevision(self, stop_revision)
898
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
799
900
return other_history[self_len:stop_revision]
802
903
def update_revisions(self, other, stop_revision=None):
803
904
"""Pull in all new revisions from other branch.
805
>>> from bzrlib.commit import commit
806
>>> bzrlib.trace.silent = True
807
>>> br1 = ScratchBranch(files=['foo', 'bar'])
810
>>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
811
>>> br2 = ScratchBranch()
812
>>> br2.update_revisions(br1)
816
>>> br2.revision_history()
818
>>> br2.update_revisions(br1)
822
>>> br1.text_store.total_size() == br2.text_store.total_size()
825
from bzrlib.progress import ProgressBar
906
from bzrlib.fetch import greedy_fetch
907
from bzrlib.revision import get_intervening_revisions
909
pb = bzrlib.ui.ui_factory.progress_bar()
829
910
pb.update('comparing histories')
830
revision_ids = self.missing_revisions(other, stop_revision)
911
if stop_revision is None:
912
other_revision = other.last_patch()
914
other_revision = other.lookup_revision(stop_revision)
915
count = greedy_fetch(self, other, other_revision, pb)[0]
917
revision_ids = self.missing_revisions(other, stop_revision)
918
except DivergedBranches, e:
920
revision_ids = get_intervening_revisions(self.last_patch(),
921
other_revision, self)
922
assert self.last_patch() not in revision_ids
923
except bzrlib.errors.NotAncestor:
926
self.append_revision(*revision_ids)
929
def install_revisions(self, other, revision_ids, pb):
930
# We are going to iterate this many times, so make sure
931
# that it is a list, and not a generator
932
revision_ids = list(revision_ids)
832
933
if hasattr(other.revision_store, "prefetch"):
833
934
other.revision_store.prefetch(revision_ids)
834
935
if hasattr(other.inventory_store, "prefetch"):
835
inventory_ids = [other.get_revision(r).inventory_id
836
for r in revision_ids]
837
936
other.inventory_store.prefetch(inventory_ids)
939
pb = bzrlib.ui.ui_factory.progress_bar()
941
# This entire next section is generally done
942
# with either generators, or bulk updates
943
inventories = other.get_inventories(revision_ids, ignore_missing=True)
840
944
needed_texts = set()
842
for rev_id in revision_ids:
844
pb.update('fetching revision', i, len(revision_ids))
845
rev = other.get_revision(rev_id)
846
revisions.append(rev)
847
inv = other.get_inventory(str(rev.inventory_id))
947
good_revisions = set()
948
for i, (inv, rev_id) in enumerate(zip(inventories, revision_ids)):
949
pb.update('fetching revision', i+1, len(revision_ids))
951
# We don't really need to get the revision here, because
952
# the only thing we needed was the inventory_id, which now
953
# is (by design) identical to the revision_id
955
# rev = other.get_revision(rev_id)
956
# except bzrlib.errors.NoSuchRevision:
957
# failures.add(rev_id)
964
good_revisions.add(rev_id)
848
967
for key, entry in inv.iter_entries():
849
968
if entry.text_id is None:
851
if entry.text_id not in self.text_store:
852
needed_texts.add(entry.text_id)
970
text_ids.append(entry.text_id)
972
has_ids = self.text_store.has(text_ids)
973
for has, text_id in zip(has_ids, text_ids):
975
needed_texts.add(text_id)
856
count = self.text_store.copy_multi(other.text_store, needed_texts)
857
print "Added %d texts." % count
858
inventory_ids = [ f.inventory_id for f in revisions ]
859
count = self.inventory_store.copy_multi(other.inventory_store,
861
print "Added %d inventories." % count
862
revision_ids = [ f.revision_id for f in revisions]
863
count = self.revision_store.copy_multi(other.revision_store,
865
for revision_id in revision_ids:
866
self.append_revision(revision_id)
867
print "Added %d revisions." % count
979
count, cp_fail = self.text_store.copy_multi(other.text_store,
981
#print "Added %d texts." % count
982
count, cp_fail = self.inventory_store.copy_multi(other.inventory_store,
984
#print "Added %d inventories." % count
985
count, cp_fail = self.revision_store.copy_multi(other.revision_store,
988
assert len(cp_fail) == 0
989
return count, failures
870
992
def commit(self, *args, **kw):
871
993
from bzrlib.commit import commit
872
994
commit(self, *args, **kw)
885
1017
revision can also be a string, in which case it is parsed for something like
886
1018
'date:' or 'revid:' etc.
1020
revno, rev_id = self._get_revision_info(revision)
1022
raise bzrlib.errors.NoSuchRevision(self, revision)
1023
return revno, rev_id
1025
def get_rev_id(self, revno, history=None):
1026
"""Find the revision id of the specified revno."""
1030
history = self.revision_history()
1031
elif revno <= 0 or revno > len(history):
1032
raise bzrlib.errors.NoSuchRevision(self, revno)
1033
return history[revno - 1]
1035
def _get_revision_info(self, revision):
1036
"""Return (revno, revision id) for revision specifier.
1038
revision can be an integer, in which case it is assumed to be revno
1039
(though this will translate negative values into positive ones)
1040
revision can also be a string, in which case it is parsed for something
1041
like 'date:' or 'revid:' etc.
1043
A revid is always returned. If it is None, the specifier referred to
1044
the null revision. If the revid does not occur in the revision
1045
history, revno will be None.
888
1048
if revision is None:
895
1055
revs = self.revision_history()
896
1056
if isinstance(revision, int):
899
# Mabye we should do this first, but we don't need it if revision == 0
900
1057
if revision < 0:
901
1058
revno = len(revs) + revision + 1
903
1060
revno = revision
1061
rev_id = self.get_rev_id(revno, revs)
904
1062
elif isinstance(revision, basestring):
905
1063
for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
906
1064
if revision.startswith(prefix):
907
revno = func(self, revs, revision)
1065
result = func(self, revs, revision)
1067
revno, rev_id = result
1070
rev_id = self.get_rev_id(revno, revs)
910
raise BzrError('No namespace registered for string: %r' % revision)
1073
raise BzrError('No namespace registered for string: %r' %
1076
raise TypeError('Unhandled revision type %s' % revision)
912
if revno is None or revno <= 0 or revno > len(revs):
913
raise BzrError("no such revision %s" % revision)
914
return revno, revs[revno-1]
1080
raise bzrlib.errors.NoSuchRevision(self, revision)
1081
return revno, rev_id
916
1083
def _namespace_revno(self, revs, revision):
917
1084
"""Lookup a revision by revision number"""
918
1085
assert revision.startswith('revno:')
920
return int(revision[6:])
1087
return (int(revision[6:]),)
921
1088
except ValueError:
923
1090
REVISION_NAMESPACES['revno:'] = _namespace_revno
925
1092
def _namespace_revid(self, revs, revision):
926
1093
assert revision.startswith('revid:')
1094
rev_id = revision[len('revid:'):]
928
return revs.index(revision[6:]) + 1
1096
return revs.index(rev_id) + 1, rev_id
929
1097
except ValueError:
931
1099
REVISION_NAMESPACES['revid:'] = _namespace_revid
933
1101
def _namespace_last(self, revs, revision):
1020
1188
# TODO: Handle timezone.
1021
1189
dt = datetime.datetime.fromtimestamp(r.timestamp)
1022
1190
if first >= dt and (last is None or dt >= last):
1025
1193
for i in range(len(revs)):
1026
1194
r = self.get_revision(revs[i])
1027
1195
# TODO: Handle timezone.
1028
1196
dt = datetime.datetime.fromtimestamp(r.timestamp)
1029
1197
if first <= dt and (last is None or dt <= last):
1031
1199
REVISION_NAMESPACES['date:'] = _namespace_date
1202
def _namespace_ancestor(self, revs, revision):
1203
from revision import common_ancestor, MultipleRevisionSources
1204
other_branch = find_branch(_trim_namespace('ancestor', revision))
1205
revision_a = self.last_patch()
1206
revision_b = other_branch.last_patch()
1207
for r, b in ((revision_a, self), (revision_b, other_branch)):
1209
raise bzrlib.errors.NoCommits(b)
1210
revision_source = MultipleRevisionSources(self, other_branch)
1211
result = common_ancestor(revision_a, revision_b, revision_source)
1213
revno = self.revision_id_to_revno(result)
1214
except bzrlib.errors.NoSuchRevision:
1219
REVISION_NAMESPACES['ancestor:'] = _namespace_ancestor
1033
1221
def revision_tree(self, revision_id):
1034
1222
"""Return Tree for a revision on this branch.
1240
def add_pending_merge(self, revision_id):
1433
def add_pending_merge(self, *revision_ids):
1241
1434
from bzrlib.revision import validate_revision_id
1243
validate_revision_id(revision_id)
1436
for rev_id in revision_ids:
1437
validate_revision_id(rev_id)
1245
1439
p = self.pending_merges()
1246
if revision_id in p:
1248
p.append(revision_id)
1249
self.set_pending_merges(p)
1441
for rev_id in revision_ids:
1447
self.set_pending_merges(p)
1252
1449
def set_pending_merges(self, rev_list):
1452
self.put_controlfile('pending-merges', '\n'.join(rev_list))
1457
def get_parent(self):
1458
"""Return the parent location of the branch.
1460
This is the default location for push/pull/missing. The usual
1461
pattern is that the user can override it by specifying a
1465
_locs = ['parent', 'pull', 'x-pull']
1468
return self.controlfile(l, 'r').read().strip('\n')
1470
if e.errno != errno.ENOENT:
1475
def set_parent(self, url):
1476
# TODO: Maybe delete old location files?
1253
1477
from bzrlib.atomicfile import AtomicFile
1254
1478
self.lock_write()
1256
f = AtomicFile(self.controlfilename('pending-merges'))
1480
f = AtomicFile(self.controlfilename('parent'))
1489
def check_revno(self, revno):
1491
Check whether a revno corresponds to any revision.
1492
Zero (the NULL revision) is considered valid.
1495
self.check_real_revno(revno)
1497
def check_real_revno(self, revno):
1499
Check whether a revno corresponds to a real revision.
1500
Zero (the NULL revision) is considered invalid
1502
if revno < 1 or revno > self.revno():
1503
raise InvalidRevisionNumber(revno)
1268
1508
class ScratchBranch(Branch):
1386
1628
"""Return a new tree-root file id."""
1387
1629
return gen_file_id('TREE_ROOT')
1632
def copy_branch(branch_from, to_location, revision=None):
1633
"""Copy branch_from into the existing directory to_location.
1636
If not None, only revisions up to this point will be copied.
1637
The head of the new branch will be that revision.
1640
The name of a local directory that exists but is empty.
1642
from bzrlib.merge import merge
1644
assert isinstance(branch_from, Branch)
1645
assert isinstance(to_location, basestring)
1647
br_to = Branch(to_location, init=True)
1648
br_to.set_root_id(branch_from.get_root_id())
1649
if revision is None:
1650
revno = branch_from.revno()
1652
revno, rev_id = branch_from.get_revision_info(revision)
1653
br_to.update_revisions(branch_from, stop_revision=revno)
1654
merge((to_location, -1), (to_location, 0), this_dir=to_location,
1655
check_clean=False, ignore_zero=True)
1656
br_to.set_parent(branch_from.base)
1659
def _trim_namespace(namespace, spec):
1660
full_namespace = namespace + ':'
1661
assert spec.startswith(full_namespace)
1662
return spec[len(full_namespace):]