15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21
from warnings import warn
22
from cStringIO import StringIO
26
from bzrlib.inventory import InventoryEntry
27
import bzrlib.inventory as inventory
21
28
from bzrlib.trace import mutter, note
22
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, splitpath, \
23
sha_file, appendpath, file_kind
24
from bzrlib.errors import BzrError
26
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
29
from bzrlib.osutils import (isdir, quotefn, compact_date, rand_bytes,
30
rename, splitpath, sha_file, appendpath,
32
import bzrlib.errors as errors
33
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
34
NoSuchRevision, HistoryMissing, NotBranchError,
35
DivergedBranches, LockError, UnlistableStore,
36
UnlistableBranch, NoSuchFile)
37
from bzrlib.textui import show_status
38
from bzrlib.revision import Revision
39
from bzrlib.delta import compare_trees
40
from bzrlib.tree import EmptyTree, RevisionTree
41
from bzrlib.inventory import Inventory
42
from bzrlib.store import copy_all
43
from bzrlib.store.compressed_text import CompressedTextStore
44
from bzrlib.store.text import TextStore
45
from bzrlib.store.weave import WeaveStore
46
import bzrlib.transactions as transactions
47
from bzrlib.transport import Transport, get_transport
52
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
53
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
54
BZR_BRANCH_FORMAT_6 = "Bazaar-NG branch, format 6\n"
27
55
## TODO: Maybe include checks for common corruption of newlines, etc?
31
def find_branch(f, **args):
32
if f and (f.startswith('http://') or f.startswith('https://')):
34
return remotebranch.RemoteBranch(f, **args)
36
return Branch(f, **args)
39
def find_cached_branch(f, cache_root, **args):
40
from remotebranch import RemoteBranch
41
br = find_branch(f, **args)
42
def cacheify(br, store_name):
43
from meta_store import CachedStore
44
cache_path = os.path.join(cache_root, store_name)
46
new_store = CachedStore(getattr(br, store_name), cache_path)
47
setattr(br, store_name, new_store)
49
if isinstance(br, RemoteBranch):
50
cacheify(br, 'inventory_store')
51
cacheify(br, 'text_store')
52
cacheify(br, 'revision_store')
58
# TODO: Some operations like log might retrieve the same revisions
59
# repeatedly to calculate deltas. We could perhaps have a weakref
60
# cache in memory to make this faster. In general anything can be
61
# cached in memory between lock and unlock operations.
63
def find_branch(*ignored, **ignored_too):
64
# XXX: leave this here for about one release, then remove it
65
raise NotImplementedError('find_branch() is not supported anymore, '
66
'please use one of the new branch constructors')
56
67
def _relpath(base, path):
57
68
"""Return path relative to base, or raise exception.
146
181
Lock object from bzrlib.lock.
183
# We actually expect this class to be somewhat short-lived; part of its
184
# purpose is to try to isolate what bits of the branch logic are tied to
185
# filesystem access, so that in a later step, we can extricate them to
186
# a separarte ("storage") class.
149
187
_lock_mode = None
150
188
_lock_count = None
190
_inventory_weave = None
153
192
# Map some sort of prefix into a namespace
154
193
# stuff like "revno:10", "revid:", etc.
155
194
# This should match a prefix with a function which accepts
156
195
REVISION_NAMESPACES = {}
158
def __init__(self, base, init=False, find_root=True):
197
def push_stores(self, branch_to):
198
"""Copy the content of this branches store to branch_to."""
199
if (self._branch_format != branch_to._branch_format
200
or self._branch_format != 4):
201
from bzrlib.fetch import greedy_fetch
202
mutter("falling back to fetch logic to push between %s(%s) and %s(%s)",
203
self, self._branch_format, branch_to, branch_to._branch_format)
204
greedy_fetch(to_branch=branch_to, from_branch=self,
205
revision=self.last_revision())
208
store_pairs = ((self.text_store, branch_to.text_store),
209
(self.inventory_store, branch_to.inventory_store),
210
(self.revision_store, branch_to.revision_store))
212
for from_store, to_store in store_pairs:
213
copy_all(from_store, to_store)
214
except UnlistableStore:
215
raise UnlistableBranch(from_store)
217
def __init__(self, transport, init=False,
218
relax_version_check=False):
159
219
"""Create new branch object at a particular location.
161
base -- Base directory for the branch.
221
transport -- A Transport object, defining how to access files.
222
(If a string, transport.transport() will be used to
223
create a Transport object)
163
225
init -- If True, create new control files in a previously
164
226
unversioned directory. If False, the branch must already
167
find_root -- If true and init is false, find the root of the
168
existing branch containing base.
229
relax_version_check -- If true, the usual check for the branch
230
version is not applied. This is intended only for
231
upgrade/recovery type use; it's not guaranteed that
232
all operations will work on old format branches.
170
234
In the test suite, creation of new trees is tested using the
171
235
`ScratchBranch` class.
173
from bzrlib.store import ImmutableStore
237
assert isinstance(transport, Transport), \
238
"%r is not a Transport" % transport
239
self._transport = transport
175
self.base = os.path.realpath(base)
176
241
self._make_control()
178
self.base = find_branch_root(base)
180
self.base = os.path.realpath(base)
181
if not isdir(self.controlfilename('.')):
182
from errors import NotBranchError
183
raise NotBranchError("not a bzr branch: %s" % quotefn(base),
184
['use "bzr init" to initialize a new working tree',
185
'current bzr can only operate from top-of-tree'])
188
self.text_store = ImmutableStore(self.controlfilename('text-store'))
189
self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
190
self.inventory_store = ImmutableStore(self.controlfilename('inventory-store'))
242
self._check_format(relax_version_check)
244
def get_store(name, compressed=True, prefixed=False):
245
# FIXME: This approach of assuming stores are all entirely compressed
246
# or entirely uncompressed is tidy, but breaks upgrade from
247
# some existing branches where there's a mixture; we probably
248
# still want the option to look for both.
249
relpath = self._rel_controlfilename(name)
251
store = CompressedTextStore(self._transport.clone(relpath),
254
store = TextStore(self._transport.clone(relpath),
256
#if self._transport.should_cache():
257
# cache_path = os.path.join(self.cache_root, name)
258
# os.mkdir(cache_path)
259
# store = bzrlib.store.CachedStore(store, cache_path)
261
def get_weave(name, prefixed=False):
262
relpath = self._rel_controlfilename(name)
263
ws = WeaveStore(self._transport.clone(relpath), prefixed=prefixed)
264
if self._transport.should_cache():
265
ws.enable_cache = True
268
if self._branch_format == 4:
269
self.inventory_store = get_store('inventory-store')
270
self.text_store = get_store('text-store')
271
self.revision_store = get_store('revision-store')
272
elif self._branch_format == 5:
273
self.control_weaves = get_weave([])
274
self.weave_store = get_weave('weaves')
275
self.revision_store = get_store('revision-store', compressed=False)
276
elif self._branch_format == 6:
277
self.control_weaves = get_weave([])
278
self.weave_store = get_weave('weaves', prefixed=True)
279
self.revision_store = get_store('revision-store', compressed=False,
281
self._transaction = None
193
283
def __str__(self):
194
return '%s(%r)' % (self.__class__.__name__, self.base)
284
return '%s(%r)' % (self.__class__.__name__, self._transport.base)
197
287
__repr__ = __str__
200
290
def __del__(self):
201
291
if self._lock_mode or self._lock:
202
from warnings import warn
292
# XXX: This should show something every time, and be suitable for
293
# headless operation and embedding
203
294
warn("branch %r was not explicitly unlocked" % self)
204
295
self._lock.unlock()
297
# TODO: It might be best to do this somewhere else,
298
# but it is nice for a Branch object to automatically
299
# cache it's information.
300
# Alternatively, we could have the Transport objects cache requests
301
# See the earlier discussion about how major objects (like Branch)
302
# should never expect their __del__ function to run.
303
if hasattr(self, 'cache_root') and self.cache_root is not None:
306
shutil.rmtree(self.cache_root)
309
self.cache_root = None
313
return self._transport.base
316
base = property(_get_base)
318
def _finish_transaction(self):
319
"""Exit the current transaction."""
320
if self._transaction is None:
321
raise errors.LockError('Branch %s is not in a transaction' %
323
transaction = self._transaction
324
self._transaction = None
327
def get_transaction(self):
328
"""Return the current active transaction.
330
If no transaction is active, this returns a passthrough object
331
for which all data is immedaitely flushed and no caching happens.
333
if self._transaction is None:
334
return transactions.PassThroughTransaction()
336
return self._transaction
338
def _set_transaction(self, new_transaction):
339
"""Set a new active transaction."""
340
if self._transaction is not None:
341
raise errors.LockError('Branch %s is in a transaction already.' %
343
self._transaction = new_transaction
208
345
def lock_write(self):
346
mutter("lock write: %s (%s)", self, self._lock_count)
347
# TODO: Upgrade locking to support using a Transport,
348
# and potentially a remote locking protocol
209
349
if self._lock_mode:
210
350
if self._lock_mode != 'w':
211
from errors import LockError
212
351
raise LockError("can't upgrade to a write lock from %r" %
214
353
self._lock_count += 1
216
from bzrlib.lock import WriteLock
218
self._lock = WriteLock(self.controlfilename('branch-lock'))
355
self._lock = self._transport.lock_write(
356
self._rel_controlfilename('branch-lock'))
219
357
self._lock_mode = 'w'
220
358
self._lock_count = 1
359
self._set_transaction(transactions.PassThroughTransaction())
224
361
def lock_read(self):
362
mutter("lock read: %s (%s)", self, self._lock_count)
225
363
if self._lock_mode:
226
364
assert self._lock_mode in ('r', 'w'), \
227
365
"invalid lock mode %r" % self._lock_mode
228
366
self._lock_count += 1
230
from bzrlib.lock import ReadLock
232
self._lock = ReadLock(self.controlfilename('branch-lock'))
368
self._lock = self._transport.lock_read(
369
self._rel_controlfilename('branch-lock'))
233
370
self._lock_mode = 'r'
234
371
self._lock_count = 1
372
self._set_transaction(transactions.ReadOnlyTransaction())
373
# 5K may be excessive, but hey, its a knob.
374
self.get_transaction().set_cache_size(5000)
238
376
def unlock(self):
377
mutter("unlock: %s (%s)", self, self._lock_count)
239
378
if not self._lock_mode:
240
from errors import LockError
241
379
raise LockError('branch %r is not locked' % (self))
243
381
if self._lock_count > 1:
244
382
self._lock_count -= 1
384
self._finish_transaction()
246
385
self._lock.unlock()
247
386
self._lock = None
248
387
self._lock_mode = self._lock_count = None
251
389
def abspath(self, name):
252
390
"""Return absolute filename for something in the branch"""
253
return os.path.join(self.base, name)
391
return self._transport.abspath(name)
256
393
def relpath(self, path):
257
394
"""Return path relative to this branch of something inside it.
259
396
Raises an error if path is not in this branch."""
260
return _relpath(self.base, path)
397
return self._transport.relpath(path)
400
def _rel_controlfilename(self, file_or_path):
401
if isinstance(file_or_path, basestring):
402
file_or_path = [file_or_path]
403
return [bzrlib.BZRDIR] + file_or_path
263
405
def controlfilename(self, file_or_path):
264
406
"""Return location relative to branch."""
265
if isinstance(file_or_path, basestring):
266
file_or_path = [file_or_path]
267
return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
407
return self._transport.abspath(self._rel_controlfilename(file_or_path))
270
410
def controlfile(self, file_or_path, mode='r'):
278
418
Controlfiles should almost never be opened in write mode but
279
419
rather should be atomically copied and replaced using atomicfile.
282
fn = self.controlfilename(file_or_path)
284
if mode == 'rb' or mode == 'wb':
285
return file(fn, mode)
286
elif mode == 'r' or mode == 'w':
287
# open in binary mode anyhow so there's no newline translation;
288
# codecs uses line buffering by default; don't want that.
290
return codecs.open(fn, mode + 'b', 'utf-8',
423
relpath = self._rel_controlfilename(file_or_path)
424
#TODO: codecs.open() buffers linewise, so it was overloaded with
425
# a much larger buffer, do we need to do the same for getreader/getwriter?
427
return self._transport.get(relpath)
429
raise BzrError("Branch.controlfile(mode='wb') is not supported, use put_controlfiles")
431
return codecs.getreader('utf-8')(self._transport.get(relpath), errors='replace')
433
raise BzrError("Branch.controlfile(mode='w') is not supported, use put_controlfiles")
293
435
raise BzrError("invalid controlfile mode %r" % mode)
437
def put_controlfile(self, path, f, encode=True):
438
"""Write an entry as a controlfile.
440
:param path: The path to put the file, relative to the .bzr control
442
:param f: A file-like or string object whose contents should be copied.
443
:param encode: If true, encode the contents as utf-8
445
self.put_controlfiles([(path, f)], encode=encode)
447
def put_controlfiles(self, files, encode=True):
448
"""Write several entries as controlfiles.
450
:param files: A list of [(path, file)] pairs, where the path is the directory
451
underneath the bzr control directory
452
:param encode: If true, encode the contents as utf-8
456
for path, f in files:
458
if isinstance(f, basestring):
459
f = f.encode('utf-8', 'replace')
461
f = codecs.getwriter('utf-8')(f, errors='replace')
462
path = self._rel_controlfilename(path)
463
ctrl_files.append((path, f))
464
self._transport.put_multi(ctrl_files)
297
466
def _make_control(self):
298
467
from bzrlib.inventory import Inventory
299
from bzrlib.xml import pack_xml
468
from bzrlib.weavefile import write_weave_v5
469
from bzrlib.weave import Weave
301
os.mkdir(self.controlfilename([]))
302
self.controlfile('README', 'w').write(
471
# Create an empty inventory
473
# if we want per-tree root ids then this is the place to set
474
# them; they're not needed for now and so ommitted for
476
bzrlib.xml5.serializer_v5.write_inventory(Inventory(), sio)
477
empty_inv = sio.getvalue()
479
bzrlib.weavefile.write_weave_v5(Weave(), sio)
480
empty_weave = sio.getvalue()
482
dirs = [[], 'revision-store', 'weaves']
303
484
"This is a Bazaar-NG control directory.\n"
304
"Do not change any files in this directory.\n")
305
self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT)
306
for d in ('text-store', 'inventory-store', 'revision-store'):
307
os.mkdir(self.controlfilename(d))
308
for f in ('revision-history', 'merged-patches',
309
'pending-merged-patches', 'branch-name',
312
self.controlfile(f, 'w').write('')
313
mutter('created control directory in ' + self.base)
315
pack_xml(Inventory(gen_root_id()), self.controlfile('inventory','w'))
318
def _check_format(self):
485
"Do not change any files in this directory.\n"),
486
('branch-format', BZR_BRANCH_FORMAT_6),
487
('revision-history', ''),
490
('pending-merges', ''),
491
('inventory', empty_inv),
492
('inventory.weave', empty_weave),
493
('ancestry.weave', empty_weave)
495
cfn = self._rel_controlfilename
496
self._transport.mkdir_multi([cfn(d) for d in dirs])
497
self.put_controlfiles(files)
498
mutter('created control directory in ' + self._transport.base)
500
def _check_format(self, relax_version_check):
319
501
"""Check this branch format is supported.
321
The current tool only supports the current unstable format.
503
The format level is stored, as an integer, in
504
self._branch_format for code that needs to check it later.
323
506
In the future, we might need different in-memory Branch
324
507
classes to support downlevel branches. But not yet.
326
# This ignores newlines so that we can open branches created
327
# on Windows from Linux and so on. I think it might be better
328
# to always make all internal files in unix format.
329
fmt = self.controlfile('branch-format', 'r').read()
330
fmt.replace('\r\n', '')
331
if fmt != BZR_BRANCH_FORMAT:
332
raise BzrError('sorry, branch format %r not supported' % fmt,
510
fmt = self.controlfile('branch-format', 'r').read()
512
raise NotBranchError(self.base)
513
mutter("got branch format %r", fmt)
514
if fmt == BZR_BRANCH_FORMAT_6:
515
self._branch_format = 6
516
elif fmt == BZR_BRANCH_FORMAT_5:
517
self._branch_format = 5
518
elif fmt == BZR_BRANCH_FORMAT_4:
519
self._branch_format = 4
521
if (not relax_version_check
522
and self._branch_format not in (5, 6)):
523
raise errors.UnsupportedFormatError(
524
'sorry, branch format %r not supported' % fmt,
333
525
['use a different bzr version',
334
'or remove the .bzr directory and "bzr init" again'])
526
'or remove the .bzr directory'
527
' and "bzr init" again'])
336
529
def get_root_id(self):
337
530
"""Return the id of this branches root"""
567
746
def append_revision(self, *revision_ids):
568
from bzrlib.atomicfile import AtomicFile
570
747
for revision_id in revision_ids:
571
748
mutter("add {%s} to revision-history" % revision_id)
573
rev_history = self.revision_history()
574
rev_history.extend(revision_ids)
576
f = AtomicFile(self.controlfilename('revision-history'))
578
for rev_id in rev_history:
751
rev_history = self.revision_history()
752
rev_history.extend(revision_ids)
753
self.put_controlfile('revision-history', '\n'.join(rev_history))
757
def has_revision(self, revision_id):
758
"""True if this branch has a copy of the revision.
760
This does not necessarily imply the revision is merge
761
or on the mainline."""
762
return (revision_id is None
763
or revision_id in self.revision_store)
765
def get_revision_xml_file(self, revision_id):
766
"""Return XML file object for revision object."""
767
if not revision_id or not isinstance(revision_id, basestring):
768
raise InvalidRevisionId(revision_id)
773
return self.revision_store[revision_id]
774
except (IndexError, KeyError):
775
raise bzrlib.errors.NoSuchRevision(self, revision_id)
780
get_revision_xml = get_revision_xml_file
782
def get_revision_xml(self, revision_id):
783
return self.get_revision_xml_file(revision_id).read()
585
786
def get_revision(self, revision_id):
586
787
"""Return the Revision object for a named revision"""
587
from bzrlib.revision import Revision
588
from bzrlib.xml import unpack_xml
788
xml_file = self.get_revision_xml_file(revision_id)
592
if not revision_id or not isinstance(revision_id, basestring):
593
raise ValueError('invalid revision-id: %r' % revision_id)
594
r = unpack_xml(Revision, self.revision_store[revision_id])
791
r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
792
except SyntaxError, e:
793
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
598
797
assert r.revision_id == revision_id
800
def get_revision_delta(self, revno):
801
"""Return the delta for one revision.
803
The delta is relative to its mainline predecessor, or the
804
empty tree for revision 1.
806
assert isinstance(revno, int)
807
rh = self.revision_history()
808
if not (1 <= revno <= len(rh)):
809
raise InvalidRevisionNumber(revno)
811
# revno is 1-based; list is 0-based
813
new_tree = self.revision_tree(rh[revno-1])
815
old_tree = EmptyTree()
817
old_tree = self.revision_tree(rh[revno-2])
819
return compare_trees(old_tree, new_tree)
602
821
def get_revision_sha1(self, revision_id):
603
822
"""Hash the stored value of a revision, and return it."""
607
826
# the revision, (add signatures/remove signatures) and still
608
827
# have all hash pointers stay consistent.
609
828
# But for now, just hash the contents.
610
return sha_file(self.revision_store[revision_id])
613
def get_inventory(self, inventory_id):
614
"""Get Inventory object by hash.
616
TODO: Perhaps for this and similar methods, take a revision
617
parameter which can be either an integer revno or a
619
from bzrlib.inventory import Inventory
620
from bzrlib.xml import unpack_xml
622
return unpack_xml(Inventory, self.inventory_store[inventory_id])
625
def get_inventory_sha1(self, inventory_id):
829
return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
831
def get_ancestry(self, revision_id):
832
"""Return a list of revision-ids integrated by a revision.
834
This currently returns a list, but the ordering is not guaranteed:
837
if revision_id is None:
839
w = self.get_inventory_weave()
840
return [None] + map(w.idx_to_name,
841
w.inclusions([w.lookup(revision_id)]))
843
def get_inventory_weave(self):
844
return self.control_weaves.get_weave('inventory',
845
self.get_transaction())
847
def get_inventory(self, revision_id):
848
"""Get Inventory object by hash."""
849
xml = self.get_inventory_xml(revision_id)
850
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
852
def get_inventory_xml(self, revision_id):
853
"""Get inventory XML as a file object."""
855
assert isinstance(revision_id, basestring), type(revision_id)
856
iw = self.get_inventory_weave()
857
return iw.get_text(iw.lookup(revision_id))
859
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
861
def get_inventory_sha1(self, revision_id):
626
862
"""Return the sha1 hash of the inventory entry
628
return sha_file(self.inventory_store[inventory_id])
864
return self.get_revision(revision_id).inventory_sha1
631
866
def get_revision_inventory(self, revision_id):
632
867
"""Return inventory of a past revision."""
633
# bzr 0.0.6 imposes the constraint that the inventory_id
868
# TODO: Unify this with get_inventory()
869
# bzr 0.0.6 and later imposes the constraint that the inventory_id
634
870
# must be the same as its revision, so this is trivial.
635
871
if revision_id == None:
636
from bzrlib.inventory import Inventory
637
872
return Inventory(self.get_root_id())
639
874
return self.get_inventory(revision_id)
642
876
def revision_history(self):
643
"""Return sequence of revision hashes on to this branch.
645
>>> ScratchBranch().revision_history()
877
"""Return sequence of revision hashes on to this branch."""
650
return [l.rstrip('\r\n') for l in
880
transaction = self.get_transaction()
881
history = transaction.map.find_revision_history()
882
if history is not None:
883
mutter("cache hit for revision-history in %s", self)
885
history = [l.rstrip('\r\n') for l in
651
886
self.controlfile('revision-history', 'r').readlines()]
887
transaction.map.add_revision_history(history)
888
# this call is disabled because revision_history is
889
# not really an object yet, and the transaction is for objects.
890
# transaction.register_clean(history, precious=True)
656
895
def common_ancestor(self, other, self_revno=None, other_revno=None):
897
>>> from bzrlib.commit import commit
659
898
>>> sb = ScratchBranch(files=['foo', 'foo~'])
660
899
>>> sb.common_ancestor(sb) == (None, None)
662
>>> commit.commit(sb, "Committing first revision", verbose=False)
901
>>> commit(sb, "Committing first revision", verbose=False)
663
902
>>> sb.common_ancestor(sb)[0]
665
904
>>> clone = sb.clone()
666
>>> commit.commit(sb, "Committing second revision", verbose=False)
905
>>> commit(sb, "Committing second revision", verbose=False)
667
906
>>> sb.common_ancestor(sb)[0]
669
908
>>> sb.common_ancestor(clone)[0]
671
>>> commit.commit(clone, "Committing divergent second revision",
910
>>> commit(clone, "Committing divergent second revision",
672
911
... verbose=False)
673
912
>>> sb.common_ancestor(clone)[0]
777
999
if stop_revision is None:
778
1000
stop_revision = other_len
779
elif stop_revision > other_len:
780
raise NoSuchRevision(self, stop_revision)
1002
assert isinstance(stop_revision, int)
1003
if stop_revision > other_len:
1004
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
782
1005
return other_history[self_len:stop_revision]
785
1007
def update_revisions(self, other, stop_revision=None):
786
"""Pull in all new revisions from other branch.
788
>>> from bzrlib.commit import commit
789
>>> bzrlib.trace.silent = True
790
>>> br1 = ScratchBranch(files=['foo', 'bar'])
793
>>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
794
>>> br2 = ScratchBranch()
795
>>> br2.update_revisions(br1)
799
>>> br2.revision_history()
801
>>> br2.update_revisions(br1)
805
>>> br1.text_store.total_size() == br2.text_store.total_size()
808
from bzrlib.progress import ProgressBar
812
pb.update('comparing histories')
813
revision_ids = self.missing_revisions(other, stop_revision)
815
if hasattr(other.revision_store, "prefetch"):
816
other.revision_store.prefetch(revision_ids)
817
if hasattr(other.inventory_store, "prefetch"):
818
inventory_ids = [other.get_revision(r).inventory_id
819
for r in revision_ids]
820
other.inventory_store.prefetch(inventory_ids)
825
for rev_id in revision_ids:
827
pb.update('fetching revision', i, len(revision_ids))
828
rev = other.get_revision(rev_id)
829
revisions.append(rev)
830
inv = other.get_inventory(str(rev.inventory_id))
831
for key, entry in inv.iter_entries():
832
if entry.text_id is None:
834
if entry.text_id not in self.text_store:
835
needed_texts.add(entry.text_id)
839
count = self.text_store.copy_multi(other.text_store, needed_texts)
840
print "Added %d texts." % count
841
inventory_ids = [ f.inventory_id for f in revisions ]
842
count = self.inventory_store.copy_multi(other.inventory_store,
844
print "Added %d inventories." % count
845
revision_ids = [ f.revision_id for f in revisions]
846
count = self.revision_store.copy_multi(other.revision_store,
848
for revision_id in revision_ids:
849
self.append_revision(revision_id)
850
print "Added %d revisions." % count
1008
"""Pull in new perfect-fit revisions."""
1009
from bzrlib.fetch import greedy_fetch
1010
from bzrlib.revision import get_intervening_revisions
1011
if stop_revision is None:
1012
stop_revision = other.last_revision()
1013
greedy_fetch(to_branch=self, from_branch=other,
1014
revision=stop_revision)
1015
pullable_revs = self.missing_revisions(
1016
other, other.revision_id_to_revno(stop_revision))
1018
greedy_fetch(to_branch=self,
1020
revision=pullable_revs[-1])
1021
self.append_revision(*pullable_revs)
853
1024
def commit(self, *args, **kw):
854
from bzrlib.commit import commit
855
commit(self, *args, **kw)
858
def lookup_revision(self, revision):
859
"""Return the revision identifier for a given revision information."""
860
revno, info = self.get_revision_info(revision)
863
def get_revision_info(self, revision):
864
"""Return (revno, revision id) for revision identifier.
866
revision can be an integer, in which case it is assumed to be revno (though
867
this will translate negative values into positive ones)
868
revision can also be a string, in which case it is parsed for something like
869
'date:' or 'revid:' etc.
874
try:# Convert to int if possible
875
revision = int(revision)
878
revs = self.revision_history()
879
if isinstance(revision, int):
882
# Mabye we should do this first, but we don't need it if revision == 0
884
revno = len(revs) + revision + 1
887
elif isinstance(revision, basestring):
888
for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
889
if revision.startswith(prefix):
890
revno = func(self, revs, revision)
893
raise BzrError('No namespace registered for string: %r' % revision)
895
if revno is None or revno <= 0 or revno > len(revs):
896
raise BzrError("no such revision %s" % revision)
897
return revno, revs[revno-1]
899
def _namespace_revno(self, revs, revision):
900
"""Lookup a revision by revision number"""
901
assert revision.startswith('revno:')
903
return int(revision[6:])
906
REVISION_NAMESPACES['revno:'] = _namespace_revno
908
def _namespace_revid(self, revs, revision):
909
assert revision.startswith('revid:')
911
return revs.index(revision[6:]) + 1
914
REVISION_NAMESPACES['revid:'] = _namespace_revid
916
def _namespace_last(self, revs, revision):
917
assert revision.startswith('last:')
919
offset = int(revision[5:])
924
raise BzrError('You must supply a positive value for --revision last:XXX')
925
return len(revs) - offset + 1
926
REVISION_NAMESPACES['last:'] = _namespace_last
928
def _namespace_tag(self, revs, revision):
929
assert revision.startswith('tag:')
930
raise BzrError('tag: namespace registered, but not implemented.')
931
REVISION_NAMESPACES['tag:'] = _namespace_tag
933
def _namespace_date(self, revs, revision):
934
assert revision.startswith('date:')
936
# Spec for date revisions:
938
# value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
939
# it can also start with a '+/-/='. '+' says match the first
940
# entry after the given date. '-' is match the first entry before the date
941
# '=' is match the first entry after, but still on the given date.
943
# +2005-05-12 says find the first matching entry after May 12th, 2005 at 0:00
944
# -2005-05-12 says find the first matching entry before May 12th, 2005 at 0:00
945
# =2005-05-12 says find the first match after May 12th, 2005 at 0:00 but before
946
# May 13th, 2005 at 0:00
948
# So the proper way of saying 'give me all entries for today' is:
949
# -r {date:+today}:{date:-tomorrow}
950
# The default is '=' when not supplied
953
if val[:1] in ('+', '-', '='):
954
match_style = val[:1]
957
today = datetime.datetime.today().replace(hour=0,minute=0,second=0,microsecond=0)
958
if val.lower() == 'yesterday':
959
dt = today - datetime.timedelta(days=1)
960
elif val.lower() == 'today':
962
elif val.lower() == 'tomorrow':
963
dt = today + datetime.timedelta(days=1)
966
# This should be done outside the function to avoid recompiling it.
967
_date_re = re.compile(
968
r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
970
r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
972
m = _date_re.match(val)
973
if not m or (not m.group('date') and not m.group('time')):
974
raise BzrError('Invalid revision date %r' % revision)
977
year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
979
year, month, day = today.year, today.month, today.day
981
hour = int(m.group('hour'))
982
minute = int(m.group('minute'))
983
if m.group('second'):
984
second = int(m.group('second'))
988
hour, minute, second = 0,0,0
990
dt = datetime.datetime(year=year, month=month, day=day,
991
hour=hour, minute=minute, second=second)
995
if match_style == '-':
997
elif match_style == '=':
998
last = dt + datetime.timedelta(days=1)
1001
for i in range(len(revs)-1, -1, -1):
1002
r = self.get_revision(revs[i])
1003
# TODO: Handle timezone.
1004
dt = datetime.datetime.fromtimestamp(r.timestamp)
1005
if first >= dt and (last is None or dt >= last):
1008
for i in range(len(revs)):
1009
r = self.get_revision(revs[i])
1010
# TODO: Handle timezone.
1011
dt = datetime.datetime.fromtimestamp(r.timestamp)
1012
if first <= dt and (last is None or dt <= last):
1014
REVISION_NAMESPACES['date:'] = _namespace_date
1025
from bzrlib.commit import Commit
1026
Commit().commit(self, *args, **kw)
1028
def revision_id_to_revno(self, revision_id):
1029
"""Given a revision id, return its revno"""
1030
if revision_id is None:
1032
history = self.revision_history()
1034
return history.index(revision_id) + 1
1036
raise bzrlib.errors.NoSuchRevision(self, revision_id)
1038
def get_rev_id(self, revno, history=None):
1039
"""Find the revision id of the specified revno."""
1043
history = self.revision_history()
1044
elif revno <= 0 or revno > len(history):
1045
raise bzrlib.errors.NoSuchRevision(self, revno)
1046
return history[revno - 1]
1016
1048
def revision_tree(self, revision_id):
1017
1049
"""Return Tree for a revision on this branch.
1019
1051
`revision_id` may be None for the null revision, in which case
1020
1052
an `EmptyTree` is returned."""
1021
from bzrlib.tree import EmptyTree, RevisionTree
1022
1053
# TODO: refactor this to use an existing revision object
1023
1054
# so we don't need to read it in twice.
1024
1055
if revision_id == None:
1025
return EmptyTree(self.get_root_id())
1027
1058
inv = self.get_revision_inventory(revision_id)
1028
return RevisionTree(self.text_store, inv)
1059
return RevisionTree(self.weave_store, inv, revision_id)
1031
1062
def working_tree(self):
1032
1063
"""Return a `Tree` for the working copy."""
1033
from workingtree import WorkingTree
1034
return WorkingTree(self.base, self.read_working_inventory())
1064
from bzrlib.workingtree import WorkingTree
1065
# TODO: In the future, WorkingTree should utilize Transport
1066
# RobertCollins 20051003 - I don't think it should - working trees are
1067
# much more complex to keep consistent than our careful .bzr subset.
1068
# instead, we should say that working trees are local only, and optimise
1070
return WorkingTree(self._transport.base, self.read_working_inventory())
1037
1073
def basis_tree(self):