191
163
self.cache_root = cache_root
194
cfg = self.tree_config()
195
return cfg.get_option(u"nickname", default=self.base.split('/')[-2])
197
def _set_nick(self, nick):
198
cfg = self.tree_config()
199
cfg.set_option(nick, "nickname")
200
assert cfg.get_option("nickname") == nick
202
nick = property(_get_nick, _set_nick)
204
def push_stores(self, branch_to):
205
"""Copy the content of this branches store to branch_to."""
206
raise NotImplementedError('push_stores is abstract')
208
def get_transaction(self):
209
"""Return the current active transaction.
211
If no transaction is active, this returns a passthrough object
212
for which all data is immediately flushed and no caching happens.
214
raise NotImplementedError('get_transaction is abstract')
216
def lock_write(self):
217
raise NotImplementedError('lock_write is abstract')
220
raise NotImplementedError('lock_read is abstract')
223
raise NotImplementedError('unlock is abstract')
225
def abspath(self, name):
226
"""Return absolute filename for something in the branch
228
XXX: Robert Collins 20051017 what is this used for? why is it a branch
229
method and not a tree method.
231
raise NotImplementedError('abspath is abstract')
233
def controlfilename(self, file_or_path):
234
"""Return location relative to branch."""
235
raise NotImplementedError('controlfilename is abstract')
237
def controlfile(self, file_or_path, mode='r'):
238
"""Open a control file for this branch.
240
There are two classes of file in the control directory: text
241
and binary. binary files are untranslated byte streams. Text
242
control files are stored with Unix newlines and in UTF-8, even
243
if the platform or locale defaults are different.
245
Controlfiles should almost never be opened in write mode but
246
rather should be atomically copied and replaced using atomicfile.
248
raise NotImplementedError('controlfile is abstract')
250
def put_controlfile(self, path, f, encode=True):
251
"""Write an entry as a controlfile.
253
:param path: The path to put the file, relative to the .bzr control
255
:param f: A file-like or string object whose contents should be copied.
256
:param encode: If true, encode the contents as utf-8
258
raise NotImplementedError('put_controlfile is abstract')
260
def put_controlfiles(self, files, encode=True):
261
"""Write several entries as controlfiles.
263
:param files: A list of [(path, file)] pairs, where the path is the directory
264
underneath the bzr control directory
265
:param encode: If true, encode the contents as utf-8
267
raise NotImplementedError('put_controlfiles is abstract')
269
def get_root_id(self):
270
"""Return the id of this branches root"""
271
raise NotImplementedError('get_root_id is abstract')
273
def set_root_id(self, file_id):
274
raise NotImplementedError('set_root_id is abstract')
276
def print_file(self, file, revision_id):
277
"""Print `file` to stdout."""
278
raise NotImplementedError('print_file is abstract')
280
def append_revision(self, *revision_ids):
281
raise NotImplementedError('append_revision is abstract')
283
def set_revision_history(self, rev_history):
284
raise NotImplementedError('set_revision_history is abstract')
286
def has_revision(self, revision_id):
287
"""True if this branch has a copy of the revision.
289
This does not necessarily imply the revision is merge
290
or on the mainline."""
291
raise NotImplementedError('has_revision is abstract')
293
def get_revision_xml(self, revision_id):
294
raise NotImplementedError('get_revision_xml is abstract')
296
def get_revision(self, revision_id):
297
"""Return the Revision object for a named revision"""
298
raise NotImplementedError('get_revision is abstract')
300
def get_revision_delta(self, revno):
301
"""Return the delta for one revision.
303
The delta is relative to its mainline predecessor, or the
304
empty tree for revision 1.
306
assert isinstance(revno, int)
307
rh = self.revision_history()
308
if not (1 <= revno <= len(rh)):
309
raise InvalidRevisionNumber(revno)
311
# revno is 1-based; list is 0-based
313
new_tree = self.revision_tree(rh[revno-1])
315
old_tree = EmptyTree()
317
old_tree = self.revision_tree(rh[revno-2])
319
return compare_trees(old_tree, new_tree)
321
def get_revision_sha1(self, revision_id):
322
"""Hash the stored value of a revision, and return it."""
323
raise NotImplementedError('get_revision_sha1 is abstract')
325
def get_ancestry(self, revision_id):
326
"""Return a list of revision-ids integrated by a revision.
328
This currently returns a list, but the ordering is not guaranteed:
331
raise NotImplementedError('get_ancestry is abstract')
333
def get_inventory(self, revision_id):
334
"""Get Inventory object by hash."""
335
raise NotImplementedError('get_inventory is abstract')
337
def get_inventory_xml(self, revision_id):
338
"""Get inventory XML as a file object."""
339
raise NotImplementedError('get_inventory_xml is abstract')
341
def get_inventory_sha1(self, revision_id):
342
"""Return the sha1 hash of the inventory entry."""
343
raise NotImplementedError('get_inventory_sha1 is abstract')
345
def get_revision_inventory(self, revision_id):
346
"""Return inventory of a past revision."""
347
raise NotImplementedError('get_revision_inventory is abstract')
349
def revision_history(self):
350
"""Return sequence of revision hashes on to this branch."""
351
raise NotImplementedError('revision_history is abstract')
354
"""Return current revision number for this branch.
356
That is equivalent to the number of revisions committed to
359
return len(self.revision_history())
361
def last_revision(self):
362
"""Return last patch hash, or None if no history."""
363
ph = self.revision_history()
369
def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
370
"""Return a list of new revisions that would perfectly fit.
372
If self and other have not diverged, return a list of the revisions
373
present in other, but missing from self.
375
>>> from bzrlib.commit import commit
376
>>> bzrlib.trace.silent = True
377
>>> br1 = ScratchBranch()
378
>>> br2 = ScratchBranch()
379
>>> br1.missing_revisions(br2)
381
>>> commit(br2, "lala!", rev_id="REVISION-ID-1")
382
>>> br1.missing_revisions(br2)
384
>>> br2.missing_revisions(br1)
386
>>> commit(br1, "lala!", rev_id="REVISION-ID-1")
387
>>> br1.missing_revisions(br2)
389
>>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
390
>>> br1.missing_revisions(br2)
392
>>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
393
>>> br1.missing_revisions(br2)
394
Traceback (most recent call last):
395
DivergedBranches: These branches have diverged. Try merge.
397
self_history = self.revision_history()
398
self_len = len(self_history)
399
other_history = other.revision_history()
400
other_len = len(other_history)
401
common_index = min(self_len, other_len) -1
402
if common_index >= 0 and \
403
self_history[common_index] != other_history[common_index]:
404
raise DivergedBranches(self, other)
406
if stop_revision is None:
407
stop_revision = other_len
409
assert isinstance(stop_revision, int)
410
if stop_revision > other_len:
411
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
412
return other_history[self_len:stop_revision]
414
def update_revisions(self, other, stop_revision=None):
415
"""Pull in new perfect-fit revisions."""
416
raise NotImplementedError('update_revisions is abstract')
418
def pullable_revisions(self, other, stop_revision):
419
raise NotImplementedError('pullable_revisions is abstract')
421
def revision_id_to_revno(self, revision_id):
422
"""Given a revision id, return its revno"""
423
if revision_id is None:
425
history = self.revision_history()
427
return history.index(revision_id) + 1
429
raise bzrlib.errors.NoSuchRevision(self, revision_id)
431
def get_rev_id(self, revno, history=None):
432
"""Find the revision id of the specified revno."""
436
history = self.revision_history()
437
elif revno <= 0 or revno > len(history):
438
raise bzrlib.errors.NoSuchRevision(self, revno)
439
return history[revno - 1]
441
def revision_tree(self, revision_id):
442
"""Return Tree for a revision on this branch.
444
`revision_id` may be None for the null revision, in which case
445
an `EmptyTree` is returned."""
446
raise NotImplementedError('revision_tree is abstract')
448
def working_tree(self):
449
"""Return a `Tree` for the working copy if this is a local branch."""
450
raise NotImplementedError('working_tree is abstract')
452
def pull(self, source, overwrite=False):
453
raise NotImplementedError('pull is abstract')
455
def basis_tree(self):
456
"""Return `Tree` object for last revision.
458
If there are no revisions yet, return an `EmptyTree`.
460
return self.revision_tree(self.last_revision())
462
def rename_one(self, from_rel, to_rel):
465
This can change the directory or the filename or both.
467
raise NotImplementedError('rename_one is abstract')
469
def move(self, from_paths, to_name):
472
to_name must exist as a versioned directory.
474
If to_name exists and is a directory, the files are moved into
475
it, keeping their old names. If it is a directory,
477
Note that to_name is only the last component of the new name;
478
this doesn't change the directory.
480
This returns a list of (from_path, to_path) pairs for each
483
raise NotImplementedError('move is abstract')
485
def get_parent(self):
486
"""Return the parent location of the branch.
488
This is the default location for push/pull/missing. The usual
489
pattern is that the user can override it by specifying a
492
raise NotImplementedError('get_parent is abstract')
494
def get_push_location(self):
495
"""Return the None or the location to push this branch to."""
496
raise NotImplementedError('get_push_location is abstract')
498
def set_push_location(self, location):
499
"""Set a new push location for this branch."""
500
raise NotImplementedError('set_push_location is abstract')
502
def set_parent(self, url):
503
raise NotImplementedError('set_parent is abstract')
505
def check_revno(self, revno):
507
Check whether a revno corresponds to any revision.
508
Zero (the NULL revision) is considered valid.
511
self.check_real_revno(revno)
513
def check_real_revno(self, revno):
515
Check whether a revno corresponds to a real revision.
516
Zero (the NULL revision) is considered invalid
518
if revno < 1 or revno > self.revno():
519
raise InvalidRevisionNumber(revno)
521
def sign_revision(self, revision_id, gpg_strategy):
522
raise NotImplementedError('sign_revision is abstract')
524
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
525
raise NotImplementedError('store_revision_signature is abstract')
528
class BzrBranchFormat(object):
529
"""An encapsulation of the initialization and open routines for a format.
531
Formats provide three things:
532
* An initialization routine,
536
Formats are placed in an dict by their format string for reference
537
during branch opening. Its not required that these be instances, they
538
can be classes themselves with class methods - it simply depends on
539
whether state is needed for a given format or not.
541
Once a format is deprecated, just deprecate the initialize and open
542
methods on the format class. Do not deprecate the object, as the
543
object will be created every time regardless.
547
"""The known formats."""
550
def find_format(klass, transport):
551
"""Return the format registered for URL."""
553
format_string = transport.get(".bzr/branch-format").read()
554
return klass._formats[format_string]
556
raise NotBranchError(path=transport.base)
558
raise errors.UnknownFormatError(format_string)
560
def get_format_string(self):
561
"""Return the ASCII format string that identifies this format."""
562
raise NotImplementedError(self.get_format_string)
564
def _find_modes(self, t):
565
"""Determine the appropriate modes for files and directories.
567
FIXME: When this merges into, or from storage,
568
this code becomes delgatable to a LockableFiles instance.
570
For now its cribbed and returns (dir_mode, file_mode)
574
except errors.TransportNotPossible:
578
dir_mode = st.st_mode & 07777
579
# Remove the sticky and execute bits for files
580
file_mode = dir_mode & ~07111
581
if not BzrBranch._set_dir_mode:
583
if not BzrBranch._set_file_mode:
585
return dir_mode, file_mode
587
def initialize(self, url):
588
"""Create a branch of this format at url and return an open branch."""
589
t = get_transport(url)
590
from bzrlib.inventory import Inventory
591
from bzrlib.weavefile import write_weave_v5
592
from bzrlib.weave import Weave
594
# Create an empty inventory
596
# if we want per-tree root ids then this is the place to set
597
# them; they're not needed for now and so ommitted for
599
bzrlib.xml5.serializer_v5.write_inventory(Inventory(), sio)
600
empty_inv = sio.getvalue()
602
bzrlib.weavefile.write_weave_v5(Weave(), sio)
603
empty_weave = sio.getvalue()
605
# Since we don't have a .bzr directory, inherit the
606
# mode from the root directory
607
dir_mode, file_mode = self._find_modes(t)
609
t.mkdir('.bzr', mode=dir_mode)
610
control = t.clone('.bzr')
611
dirs = ['revision-store', 'weaves']
613
StringIO("This is a Bazaar-NG control directory.\n"
614
"Do not change any files in this directory.\n")),
615
('branch-format', StringIO(self.get_format_string())),
616
('revision-history', StringIO('')),
617
('branch-name', StringIO('')),
618
('branch-lock', StringIO('')),
619
('pending-merges', StringIO('')),
620
('inventory', StringIO(empty_inv)),
621
('inventory.weave', StringIO(empty_weave)),
622
('ancestry.weave', StringIO(empty_weave))
624
control.mkdir_multi(dirs, mode=dir_mode)
625
control.put_multi(files, mode=file_mode)
626
mutter('created control directory in ' + t.base)
627
return BzrBranch(t, format=self)
629
def is_supported(self):
630
"""Is this format supported?
632
Supported formats can be initialized and opened.
633
Unsupported formats may not support initialization or committing or
634
some other features depending on the reason for not being supported.
638
def open(self, transport):
639
"""Fill out the data in branch for the branch at url."""
640
return BzrBranch(transport, format=self)
643
def register_format(klass, format):
644
klass._formats[format.get_format_string()] = format
647
def unregister_format(klass, format):
648
assert klass._formats[format.get_format_string()] is format
649
del klass._formats[format.get_format_string()]
652
class BzrBranchFormat4(BzrBranchFormat):
653
"""Bzr branch format 4.
657
- TextStores for texts, inventories,revisions.
659
This format is deprecated: it indexes texts using a text it which is
660
removed in format 5; write support for this format has been removed.
663
def get_format_string(self):
664
"""See BzrBranchFormat.get_format_string()."""
665
return BZR_BRANCH_FORMAT_4
667
def initialize(self, url):
668
"""Format 4 branches cannot be created."""
669
raise UninitializableFormat(self)
671
def is_supported(self):
672
"""Format 4 is not supported.
674
It is not supported because the model changed from 4 to 5 and the
675
conversion logic is expensive - so doing it on the fly was not
681
class BzrBranchFormat5(BzrBranchFormat):
682
"""Bzr branch format 5.
685
- weaves for file texts and inventory
687
- TextStores for revisions and signatures.
690
def get_format_string(self):
691
"""See BzrBranchFormat.get_format_string()."""
692
return BZR_BRANCH_FORMAT_5
695
class BzrBranchFormat6(BzrBranchFormat):
696
"""Bzr branch format 6.
699
- weaves for file texts and inventory
700
- hash subdirectory based stores.
701
- TextStores for revisions and signatures.
704
def get_format_string(self):
705
"""See BzrBranchFormat.get_format_string()."""
706
return BZR_BRANCH_FORMAT_6
709
BzrBranchFormat.register_format(BzrBranchFormat4())
710
BzrBranchFormat.register_format(BzrBranchFormat5())
711
BzrBranchFormat.register_format(BzrBranchFormat6())
714
class BzrBranch(Branch):
166
class _Branch(Branch):
715
167
"""A branch stored in the actual filesystem.
717
169
Note that it's "local" in the context of the filesystem; it doesn't
1003
461
f = codecs.getwriter('utf-8')(f, errors='replace')
1004
462
path = self._rel_controlfilename(path)
1005
463
ctrl_files.append((path, f))
1006
self._transport.put_multi(ctrl_files, mode=self._file_mode)
1008
def _find_modes(self, path=None):
1009
"""Determine the appropriate modes for files and directories."""
1012
path = self._rel_controlfilename('')
1013
st = self._transport.stat(path)
1014
except errors.TransportNotPossible:
1015
self._dir_mode = 0755
1016
self._file_mode = 0644
1018
self._dir_mode = st.st_mode & 07777
1019
# Remove the sticky and execute bits for files
1020
self._file_mode = self._dir_mode & ~07111
1021
if not self._set_dir_mode:
1022
self._dir_mode = None
1023
if not self._set_file_mode:
1024
self._file_mode = None
1026
def _check_format(self, format):
1027
"""Identify the branch format if needed.
1029
The format is stored as a reference to the format object in
464
self._transport.put_multi(ctrl_files)
466
def _make_control(self):
467
from bzrlib.inventory import Inventory
468
from bzrlib.weavefile import write_weave_v5
469
from bzrlib.weave import Weave
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']
484
"This is a Bazaar-NG control directory.\n"
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):
501
"""Check this branch format is supported.
503
The format level is stored, as an integer, in
1030
504
self._branch_format for code that needs to check it later.
1032
The format parameter is either None or the branch format class
1033
used to open this branch.
506
In the future, we might need different in-memory Branch
507
classes to support downlevel branches. But not yet.
1036
format = BzrBranchFormat.find_format(self._transport)
1037
self._branch_format = format
1038
mutter("got branch format %s", self._branch_format)
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,
525
['use a different bzr version',
526
'or remove the .bzr directory'
527
' and "bzr init" again'])
1041
529
def get_root_id(self):
1042
"""See Branch.get_root_id."""
1043
inv = self.get_inventory(self.last_revision())
530
"""Return the id of this branches root"""
531
inv = self.read_working_inventory()
1044
532
return inv.root.file_id
1047
def print_file(self, file, revision_id):
1048
"""See Branch.print_file."""
1049
tree = self.revision_tree(revision_id)
1050
# use inventory as it was in that revision
1051
file_id = tree.inventory.path2id(file)
1054
revno = self.revision_id_to_revno(revision_id)
1055
except errors.NoSuchRevision:
1056
# TODO: This should not be BzrError,
1057
# but NoSuchFile doesn't fit either
1058
raise BzrError('%r is not present in revision %s'
1059
% (file, revision_id))
534
def set_root_id(self, file_id):
535
inv = self.read_working_inventory()
536
orig_root_id = inv.root.file_id
537
del inv._byid[inv.root.file_id]
538
inv.root.file_id = file_id
539
inv._byid[inv.root.file_id] = inv.root
542
if entry.parent_id in (None, orig_root_id):
543
entry.parent_id = inv.root.file_id
544
self._write_inventory(inv)
546
def read_working_inventory(self):
547
"""Read the working inventory."""
550
# ElementTree does its own conversion from UTF-8, so open in
552
f = self.controlfile('inventory', 'rb')
553
return bzrlib.xml5.serializer_v5.read_inventory(f)
558
def _write_inventory(self, inv):
559
"""Update the working inventory.
561
That is to say, the inventory describing changes underway, that
562
will be committed to the next revision.
564
from cStringIO import StringIO
568
bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
570
# Transport handles atomicity
571
self.put_controlfile('inventory', sio)
575
mutter('wrote working inventory')
577
inventory = property(read_working_inventory, _write_inventory, None,
578
"""Inventory for the working copy.""")
580
def add(self, files, ids=None):
581
"""Make files versioned.
583
Note that the command line normally calls smart_add instead,
584
which can automatically recurse.
586
This puts the files in the Added state, so that they will be
587
recorded by the next commit.
590
List of paths to add, relative to the base of the tree.
593
If set, use these instead of automatically generated ids.
594
Must be the same length as the list of files, but may
595
contain None for ids that are to be autogenerated.
597
TODO: Perhaps have an option to add the ids even if the files do
600
TODO: Perhaps yield the ids and paths as they're added.
602
# TODO: Re-adding a file that is removed in the working copy
603
# should probably put it back with the previous ID.
604
if isinstance(files, basestring):
605
assert(ids is None or isinstance(ids, basestring))
611
ids = [None] * len(files)
613
assert(len(ids) == len(files))
617
inv = self.read_working_inventory()
618
for f,file_id in zip(files, ids):
619
if is_control_file(f):
620
raise BzrError("cannot add control file %s" % quotefn(f))
625
raise BzrError("cannot add top-level %r" % f)
627
fullpath = os.path.normpath(self.abspath(f))
630
kind = file_kind(fullpath)
632
# maybe something better?
633
raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
635
if not InventoryEntry.versionable_kind(kind):
636
raise BzrError('cannot add: not a versionable file ('
637
'i.e. regular file, symlink or directory): %s' % quotefn(f))
640
file_id = gen_file_id(f)
641
inv.add_path(f, kind=kind, file_id=file_id)
643
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
645
self._write_inventory(inv)
650
def print_file(self, file, revno):
651
"""Print `file` to stdout."""
654
tree = self.revision_tree(self.get_rev_id(revno))
655
# use inventory as it was in that revision
656
file_id = tree.inventory.path2id(file)
658
raise BzrError("%r is not present in revision %s" % (file, revno))
659
tree.print_file(file_id)
664
def remove(self, files, verbose=False):
665
"""Mark nominated files for removal from the inventory.
667
This does not remove their text. This does not run on
669
TODO: Refuse to remove modified files unless --force is given?
671
TODO: Do something useful with directories.
673
TODO: Should this remove the text or not? Tough call; not
674
removing may be useful and the user can just use use rm, and
675
is the opposite of add. Removing it is consistent with most
676
other tools. Maybe an option.
678
## TODO: Normalize names
679
## TODO: Remove nested loops; better scalability
680
if isinstance(files, basestring):
686
tree = self.working_tree()
689
# do this before any modifications
693
raise BzrError("cannot remove unversioned file %s" % quotefn(f))
694
mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
696
# having remove it, it must be either ignored or unknown
697
if tree.is_ignored(f):
701
show_status(new_status, inv[fid].kind, quotefn(f))
704
self._write_inventory(inv)
708
# FIXME: this doesn't need to be a branch method
709
def set_inventory(self, new_inventory_list):
710
from bzrlib.inventory import Inventory, InventoryEntry
711
inv = Inventory(self.get_root_id())
712
for path, file_id, parent, kind in new_inventory_list:
713
name = os.path.basename(path)
716
# fixme, there should be a factory function inv,add_??
717
if kind == 'directory':
718
inv.add(inventory.InventoryDirectory(file_id, name, parent))
720
inv.add(inventory.InventoryFile(file_id, name, parent))
721
elif kind == 'symlink':
722
inv.add(inventory.InventoryLink(file_id, name, parent))
1061
raise BzrError('%r is not present in revision %s'
1063
tree.print_file(file_id)
724
raise BzrError("unknown kind %r" % kind)
725
self._write_inventory(inv)
728
"""Return all unknown files.
730
These are files in the working directory that are not versioned or
731
control files or ignored.
733
>>> b = ScratchBranch(files=['foo', 'foo~'])
734
>>> list(b.unknowns())
737
>>> list(b.unknowns())
740
>>> list(b.unknowns())
743
return self.working_tree().unknowns()
1066
746
def append_revision(self, *revision_ids):
1067
"""See Branch.append_revision."""
1068
747
for revision_id in revision_ids:
1069
748
mutter("add {%s} to revision-history" % revision_id)
1070
rev_history = self.revision_history()
1071
rev_history.extend(revision_ids)
1072
self.set_revision_history(rev_history)
1075
def set_revision_history(self, rev_history):
1076
"""See Branch.set_revision_history."""
1077
old_revision = self.last_revision()
1078
new_revision = rev_history[-1]
1079
self.put_controlfile('revision-history', '\n'.join(rev_history))
1081
self.working_tree().set_last_revision(new_revision, old_revision)
1082
except NoWorkingTree:
1083
mutter('Unable to set_last_revision without a working tree.')
751
rev_history = self.revision_history()
752
rev_history.extend(revision_ids)
753
self.put_controlfile('revision-history', '\n'.join(rev_history))
1085
757
def has_revision(self, revision_id):
1086
"""See Branch.has_revision."""
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."""
1087
762
return (revision_id is None
1088
or self.revision_store.has_id(revision_id))
763
or revision_id in self.revision_store)
1091
def _get_revision_xml_file(self, revision_id):
765
def get_revision_xml_file(self, revision_id):
766
"""Return XML file object for revision object."""
1092
767
if not revision_id or not isinstance(revision_id, basestring):
1093
raise InvalidRevisionId(revision_id=revision_id, branch=self)
768
raise InvalidRevisionId(revision_id)
1095
return self.revision_store.get(revision_id)
1096
except (IndexError, KeyError):
1097
raise bzrlib.errors.NoSuchRevision(self, 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
1099
782
def get_revision_xml(self, revision_id):
1100
"""See Branch.get_revision_xml."""
1101
return self._get_revision_xml_file(revision_id).read()
783
return self.get_revision_xml_file(revision_id).read()
1103
786
def get_revision(self, revision_id):
1104
"""See Branch.get_revision."""
1105
xml_file = self._get_revision_xml_file(revision_id)
787
"""Return the Revision object for a named revision"""
788
xml_file = self.get_revision_xml_file(revision_id)
1108
791
r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
1125
829
return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
1127
831
def get_ancestry(self, revision_id):
1128
"""See Branch.get_ancestry."""
832
"""Return a list of revision-ids integrated by a revision.
834
This currently returns a list, but the ordering is not guaranteed:
1129
837
if revision_id is None:
1131
w = self._get_inventory_weave()
839
w = self.get_inventory_weave()
1132
840
return [None] + map(w.idx_to_name,
1133
841
w.inclusions([w.lookup(revision_id)]))
1135
def _get_inventory_weave(self):
843
def get_inventory_weave(self):
1136
844
return self.control_weaves.get_weave('inventory',
1137
845
self.get_transaction())
1139
847
def get_inventory(self, revision_id):
1140
"""See Branch.get_inventory."""
848
"""Get Inventory object by hash."""
1141
849
xml = self.get_inventory_xml(revision_id)
1142
850
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
1144
852
def get_inventory_xml(self, revision_id):
1145
"""See Branch.get_inventory_xml."""
853
"""Get inventory XML as a file object."""
1147
855
assert isinstance(revision_id, basestring), type(revision_id)
1148
iw = self._get_inventory_weave()
856
iw = self.get_inventory_weave()
1149
857
return iw.get_text(iw.lookup(revision_id))
1150
858
except IndexError:
1151
859
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
1153
861
def get_inventory_sha1(self, revision_id):
1154
"""See Branch.get_inventory_sha1."""
862
"""Return the sha1 hash of the inventory entry
1155
864
return self.get_revision(revision_id).inventory_sha1
1157
866
def get_revision_inventory(self, revision_id):
1158
"""See Branch.get_revision_inventory."""
867
"""Return inventory of a past revision."""
1159
868
# TODO: Unify this with get_inventory()
1160
869
# bzr 0.0.6 and later imposes the constraint that the inventory_id
1161
870
# must be the same as its revision, so this is trivial.
1162
871
if revision_id == None:
1163
# This does not make sense: if there is no revision,
1164
# then it is the current tree inventory surely ?!
1165
# and thus get_root_id() is something that looks at the last
1166
# commit on the branch, and the get_root_id is an inventory check.
1167
raise NotImplementedError
1168
# return Inventory(self.get_root_id())
872
return Inventory(self.get_root_id())
1170
874
return self.get_inventory(revision_id)
1173
876
def revision_history(self):
1174
"""See Branch.revision_history."""
1175
transaction = self.get_transaction()
1176
history = transaction.map.find_revision_history()
1177
if history is not None:
1178
mutter("cache hit for revision-history in %s", self)
877
"""Return sequence of revision hashes on to this branch."""
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
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)
1179
891
return list(history)
1180
history = [l.rstrip('\r\n') for l in
1181
self.controlfile('revision-history', 'r').readlines()]
1182
transaction.map.add_revision_history(history)
1183
# this call is disabled because revision_history is
1184
# not really an object yet, and the transaction is for objects.
1185
# transaction.register_clean(history, precious=True)
1186
return list(history)
895
def common_ancestor(self, other, self_revno=None, other_revno=None):
897
>>> from bzrlib.commit import commit
898
>>> sb = ScratchBranch(files=['foo', 'foo~'])
899
>>> sb.common_ancestor(sb) == (None, None)
901
>>> commit(sb, "Committing first revision", verbose=False)
902
>>> sb.common_ancestor(sb)[0]
904
>>> clone = sb.clone()
905
>>> commit(sb, "Committing second revision", verbose=False)
906
>>> sb.common_ancestor(sb)[0]
908
>>> sb.common_ancestor(clone)[0]
910
>>> commit(clone, "Committing divergent second revision",
912
>>> sb.common_ancestor(clone)[0]
914
>>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
916
>>> sb.common_ancestor(sb) != clone.common_ancestor(clone)
918
>>> clone2 = sb.clone()
919
>>> sb.common_ancestor(clone2)[0]
921
>>> sb.common_ancestor(clone2, self_revno=1)[0]
923
>>> sb.common_ancestor(clone2, other_revno=1)[0]
926
my_history = self.revision_history()
927
other_history = other.revision_history()
928
if self_revno is None:
929
self_revno = len(my_history)
930
if other_revno is None:
931
other_revno = len(other_history)
932
indices = range(min((self_revno, other_revno)))
935
if my_history[r] == other_history[r]:
936
return r+1, my_history[r]
941
"""Return current revision number for this branch.
943
That is equivalent to the number of revisions committed to
946
return len(self.revision_history())
949
def last_revision(self):
950
"""Return last patch hash, or None if no history.
952
ph = self.revision_history()
959
def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
960
"""Return a list of new revisions that would perfectly fit.
962
If self and other have not diverged, return a list of the revisions
963
present in other, but missing from self.
965
>>> from bzrlib.commit import commit
966
>>> bzrlib.trace.silent = True
967
>>> br1 = ScratchBranch()
968
>>> br2 = ScratchBranch()
969
>>> br1.missing_revisions(br2)
971
>>> commit(br2, "lala!", rev_id="REVISION-ID-1")
972
>>> br1.missing_revisions(br2)
974
>>> br2.missing_revisions(br1)
976
>>> commit(br1, "lala!", rev_id="REVISION-ID-1")
977
>>> br1.missing_revisions(br2)
979
>>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
980
>>> br1.missing_revisions(br2)
982
>>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
983
>>> br1.missing_revisions(br2)
984
Traceback (most recent call last):
985
DivergedBranches: These branches have diverged.
987
# FIXME: If the branches have diverged, but the latest
988
# revision in this branch is completely merged into the other,
989
# then we should still be able to pull.
990
self_history = self.revision_history()
991
self_len = len(self_history)
992
other_history = other.revision_history()
993
other_len = len(other_history)
994
common_index = min(self_len, other_len) -1
995
if common_index >= 0 and \
996
self_history[common_index] != other_history[common_index]:
997
raise DivergedBranches(self, other)
999
if stop_revision is None:
1000
stop_revision = other_len
1002
assert isinstance(stop_revision, int)
1003
if stop_revision > other_len:
1004
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
1005
return other_history[self_len:stop_revision]
1188
1007
def update_revisions(self, other, stop_revision=None):
1189
"""See Branch.update_revisions."""
1008
"""Pull in new perfect-fit revisions."""
1190
1009
from bzrlib.fetch import greedy_fetch
1010
from bzrlib.revision import get_intervening_revisions
1191
1011
if stop_revision is None:
1192
1012
stop_revision = other.last_revision()
1193
### Should this be checking is_ancestor instead of revision_history?
1194
if (stop_revision is not None and
1195
stop_revision in self.revision_history()):
1013
if stop_revision is not None and self.has_revision(stop_revision):
1197
1015
greedy_fetch(to_branch=self, from_branch=other,
1198
1016
revision=stop_revision)
1199
pullable_revs = self.pullable_revisions(other, stop_revision)
1200
if len(pullable_revs) > 0:
1017
pullable_revs = self.missing_revisions(
1018
other, other.revision_id_to_revno(stop_revision))
1020
greedy_fetch(to_branch=self,
1022
revision=pullable_revs[-1])
1201
1023
self.append_revision(*pullable_revs)
1203
def pullable_revisions(self, other, stop_revision):
1204
"""See Branch.pullable_revisions."""
1205
other_revno = other.revision_id_to_revno(stop_revision)
1026
def commit(self, *args, **kw):
1027
from bzrlib.commit import Commit
1028
Commit().commit(self, *args, **kw)
1030
def revision_id_to_revno(self, revision_id):
1031
"""Given a revision id, return its revno"""
1032
if revision_id is None:
1034
history = self.revision_history()
1207
return self.missing_revisions(other, other_revno)
1208
except DivergedBranches, e:
1210
pullable_revs = get_intervening_revisions(self.last_revision(),
1211
stop_revision, self)
1212
assert self.last_revision() not in pullable_revs
1213
return pullable_revs
1214
except bzrlib.errors.NotAncestor:
1215
if is_ancestor(self.last_revision(), stop_revision, self):
1036
return history.index(revision_id) + 1
1038
raise bzrlib.errors.NoSuchRevision(self, revision_id)
1040
def get_rev_id(self, revno, history=None):
1041
"""Find the revision id of the specified revno."""
1045
history = self.revision_history()
1046
elif revno <= 0 or revno > len(history):
1047
raise bzrlib.errors.NoSuchRevision(self, revno)
1048
return history[revno - 1]
1220
1050
def revision_tree(self, revision_id):
1221
"""See Branch.revision_tree."""
1051
"""Return Tree for a revision on this branch.
1053
`revision_id` may be None for the null revision, in which case
1054
an `EmptyTree` is returned."""
1222
1055
# TODO: refactor this to use an existing revision object
1223
1056
# so we don't need to read it in twice.
1224
if revision_id == None or revision_id == NULL_REVISION:
1057
if revision_id == None:
1225
1058
return EmptyTree()
1227
1060
inv = self.get_revision_inventory(revision_id)
1228
return RevisionTree(self, inv, revision_id)
1061
return RevisionTree(self.weave_store, inv, revision_id)
1230
def basis_tree(self):
1231
"""See Branch.basis_tree."""
1233
revision_id = self.revision_history()[-1]
1234
xml = self.working_tree().read_basis_inventory(revision_id)
1235
inv = bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
1236
return RevisionTree(self, inv, revision_id)
1237
except (IndexError, NoSuchFile, NoWorkingTree), e:
1238
return self.revision_tree(self.last_revision())
1240
1064
def working_tree(self):
1241
"""See Branch.working_tree."""
1065
"""Return a `Tree` for the working copy."""
1242
1066
from bzrlib.workingtree import WorkingTree
1243
if self._transport.base.find('://') != -1:
1244
raise NoWorkingTree(self.base)
1245
return WorkingTree(self.base, branch=self)
1248
def pull(self, source, overwrite=False):
1249
"""See Branch.pull."""
1252
old_count = len(self.revision_history())
1254
self.update_revisions(source)
1255
except DivergedBranches:
1259
self.set_revision_history(source.revision_history())
1260
new_count = len(self.revision_history())
1261
return new_count - old_count
1067
# TODO: In the future, WorkingTree should utilize Transport
1068
# RobertCollins 20051003 - I don't think it should - working trees are
1069
# much more complex to keep consistent than our careful .bzr subset.
1070
# instead, we should say that working trees are local only, and optimise
1072
return WorkingTree(self._transport.base, self.read_working_inventory())
1075
def basis_tree(self):
1076
"""Return `Tree` object for last revision.
1078
If there are no revisions yet, return an `EmptyTree`.
1080
return self.revision_tree(self.last_revision())
1083
def rename_one(self, from_rel, to_rel):
1086
This can change the directory or the filename or both.
1090
tree = self.working_tree()
1091
inv = tree.inventory
1092
if not tree.has_filename(from_rel):
1093
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
1094
if tree.has_filename(to_rel):
1095
raise BzrError("can't rename: new working file %r already exists" % to_rel)
1097
file_id = inv.path2id(from_rel)
1099
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
1101
if inv.path2id(to_rel):
1102
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
1104
to_dir, to_tail = os.path.split(to_rel)
1105
to_dir_id = inv.path2id(to_dir)
1106
if to_dir_id == None and to_dir != '':
1107
raise BzrError("can't determine destination directory id for %r" % to_dir)
1109
mutter("rename_one:")
1110
mutter(" file_id {%s}" % file_id)
1111
mutter(" from_rel %r" % from_rel)
1112
mutter(" to_rel %r" % to_rel)
1113
mutter(" to_dir %r" % to_dir)
1114
mutter(" to_dir_id {%s}" % to_dir_id)
1116
inv.rename(file_id, to_dir_id, to_tail)
1118
from_abs = self.abspath(from_rel)
1119
to_abs = self.abspath(to_rel)
1121
rename(from_abs, to_abs)
1123
raise BzrError("failed to rename %r to %r: %s"
1124
% (from_abs, to_abs, e[1]),
1125
["rename rolled back"])
1127
self._write_inventory(inv)
1132
def move(self, from_paths, to_name):
1135
to_name must exist as a versioned directory.
1137
If to_name exists and is a directory, the files are moved into
1138
it, keeping their old names. If it is a directory,
1140
Note that to_name is only the last component of the new name;
1141
this doesn't change the directory.
1143
This returns a list of (from_path, to_path) pairs for each
1144
entry that is moved.
1149
## TODO: Option to move IDs only
1150
assert not isinstance(from_paths, basestring)
1151
tree = self.working_tree()
1152
inv = tree.inventory
1153
to_abs = self.abspath(to_name)
1154
if not isdir(to_abs):
1155
raise BzrError("destination %r is not a directory" % to_abs)
1156
if not tree.has_filename(to_name):
1157
raise BzrError("destination %r not in working directory" % to_abs)
1158
to_dir_id = inv.path2id(to_name)
1159
if to_dir_id == None and to_name != '':
1160
raise BzrError("destination %r is not a versioned directory" % to_name)
1161
to_dir_ie = inv[to_dir_id]
1162
if to_dir_ie.kind not in ('directory', 'root_directory'):
1163
raise BzrError("destination %r is not a directory" % to_abs)
1165
to_idpath = inv.get_idpath(to_dir_id)
1167
for f in from_paths:
1168
if not tree.has_filename(f):
1169
raise BzrError("%r does not exist in working tree" % f)
1170
f_id = inv.path2id(f)
1172
raise BzrError("%r is not versioned" % f)
1173
name_tail = splitpath(f)[-1]
1174
dest_path = appendpath(to_name, name_tail)
1175
if tree.has_filename(dest_path):
1176
raise BzrError("destination %r already exists" % dest_path)
1177
if f_id in to_idpath:
1178
raise BzrError("can't move %r to a subdirectory of itself" % f)
1180
# OK, so there's a race here, it's possible that someone will
1181
# create a file in this interval and then the rename might be
1182
# left half-done. But we should have caught most problems.
1184
for f in from_paths:
1185
name_tail = splitpath(f)[-1]
1186
dest_path = appendpath(to_name, name_tail)
1187
result.append((f, dest_path))
1188
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1190
rename(self.abspath(f), self.abspath(dest_path))
1192
raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1193
["rename rolled back"])
1195
self._write_inventory(inv)
1202
def revert(self, filenames, old_tree=None, backups=True):
1203
"""Restore selected files to the versions from a previous tree.
1206
If true (default) backups are made of files before
1209
from bzrlib.errors import NotVersionedError, BzrError
1210
from bzrlib.atomicfile import AtomicFile
1211
from bzrlib.osutils import backup_file
1213
inv = self.read_working_inventory()
1214
if old_tree is None:
1215
old_tree = self.basis_tree()
1216
old_inv = old_tree.inventory
1219
for fn in filenames:
1220
file_id = inv.path2id(fn)
1222
raise NotVersionedError("not a versioned file", fn)
1223
if not old_inv.has_id(file_id):
1224
raise BzrError("file not present in old tree", fn, file_id)
1225
nids.append((fn, file_id))
1227
# TODO: Rename back if it was previously at a different location
1229
# TODO: If given a directory, restore the entire contents from
1230
# the previous version.
1232
# TODO: Make a backup to a temporary file.
1234
# TODO: If the file previously didn't exist, delete it?
1235
for fn, file_id in nids:
1238
f = AtomicFile(fn, 'wb')
1240
f.write(old_tree.get_file(file_id).read())
1246
def pending_merges(self):
1247
"""Return a list of pending merges.
1249
These are revisions that have been merged into the working
1250
directory but not yet committed.
1252
cfn = self._rel_controlfilename('pending-merges')
1253
if not self._transport.has(cfn):
1256
for l in self.controlfile('pending-merges', 'r').readlines():
1257
p.append(l.rstrip('\n'))
1261
def add_pending_merge(self, *revision_ids):
1262
# TODO: Perhaps should check at this point that the
1263
# history of the revision is actually present?
1264
p = self.pending_merges()
1266
for rev_id in revision_ids:
1272
self.set_pending_merges(p)
1274
def set_pending_merges(self, rev_list):
1277
self.put_controlfile('pending-merges', '\n'.join(rev_list))
1265
1282
def get_parent(self):
1266
"""See Branch.get_parent."""
1283
"""Return the parent location of the branch.
1285
This is the default location for push/pull/missing. The usual
1286
pattern is that the user can override it by specifying a
1268
1290
_locs = ['parent', 'pull', 'x-pull']
1269
1291
for l in _locs:
1271
1293
return self.controlfile(l, 'r').read().strip('\n')
1295
if e.errno != errno.ENOENT:
1276
def get_push_location(self):
1277
"""See Branch.get_push_location."""
1278
config = bzrlib.config.BranchConfig(self)
1279
push_loc = config.get_user_option('push_location')
1282
def set_push_location(self, location):
1283
"""See Branch.set_push_location."""
1284
config = bzrlib.config.LocationConfig(self.base)
1285
config.set_user_option('push_location', location)
1288
1300
def set_parent(self, url):
1289
"""See Branch.set_parent."""
1290
1301
# TODO: Maybe delete old location files?
1291
1302
from bzrlib.atomicfile import AtomicFile
1292
f = AtomicFile(self.controlfilename('parent'))
1305
f = AtomicFile(self.controlfilename('parent'))
1299
def tree_config(self):
1300
return TreeConfig(self)
1302
def sign_revision(self, revision_id, gpg_strategy):
1303
"""See Branch.sign_revision."""
1304
plaintext = Testament.from_revision(self, revision_id).as_short_text()
1305
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
1308
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1309
"""See Branch.store_revision_signature."""
1310
self.revision_store.add(StringIO(gpg_strategy.sign(plaintext)),
1314
Branch.set_default_initializer(BzrBranch._initialize)
1317
class BranchTestProviderAdapter(object):
1318
"""A tool to generate a suite testing multiple branch formats at once.
1320
This is done by copying the test once for each transport and injecting
1321
the transport_server, transport_readonly_server, and branch_format
1322
classes into each copy. Each copy is also given a new id() to make it
1326
def __init__(self, transport_server, transport_readonly_server, formats):
1327
self._transport_server = transport_server
1328
self._transport_readonly_server = transport_readonly_server
1329
self._formats = formats
1331
def adapt(self, test):
1332
result = TestSuite()
1333
for format in self._formats:
1334
new_test = deepcopy(test)
1335
new_test.transport_server = self._transport_server
1336
new_test.transport_readonly_server = self._transport_readonly_server
1337
new_test.branch_format = format
1338
def make_new_test_id():
1339
new_id = "%s(%s)" % (new_test.id(), format.__class__.__name__)
1340
return lambda: new_id
1341
new_test.id = make_new_test_id()
1342
result.addTest(new_test)
1346
class ScratchBranch(BzrBranch):
1314
def check_revno(self, revno):
1316
Check whether a revno corresponds to any revision.
1317
Zero (the NULL revision) is considered valid.
1320
self.check_real_revno(revno)
1322
def check_real_revno(self, revno):
1324
Check whether a revno corresponds to a real revision.
1325
Zero (the NULL revision) is considered invalid
1327
if revno < 1 or revno > self.revno():
1328
raise InvalidRevisionNumber(revno)
1334
class ScratchBranch(_Branch):
1347
1335
"""Special test class: a branch that cleans up after itself.
1349
1337
>>> b = ScratchBranch()
1350
1338
>>> isdir(b.base)
1352
1340
>>> bd = b.base
1353
>>> b._transport.__del__()
1358
def __init__(self, files=[], dirs=[], transport=None):
1345
def __init__(self, files=[], dirs=[], base=None):
1359
1346
"""Make a test branch.
1361
1348
This creates a temporary directory and runs init-tree in it.
1363
1350
If any files are listed, they are created in the working copy.
1365
if transport is None:
1366
transport = bzrlib.transport.local.ScratchTransport()
1367
Branch.initialize(transport.base)
1368
super(ScratchBranch, self).__init__(transport)
1370
super(ScratchBranch, self).__init__(transport)
1352
from tempfile import mkdtemp
1357
if isinstance(base, basestring):
1358
base = get_transport(base)
1359
_Branch.__init__(self, base, init=init)
1373
1361
self._transport.mkdir(d)