152
154
self.cache_root = cache_root
155
class _Branch(Branch):
157
cfg = self.tree_config()
158
return cfg.get_option(u"nickname", default=self.base.split('/')[-1])
160
def _set_nick(self, nick):
161
cfg = self.tree_config()
162
cfg.set_option(nick, "nickname")
163
assert cfg.get_option("nickname") == nick
165
nick = property(_get_nick, _set_nick)
167
def push_stores(self, branch_to):
168
"""Copy the content of this branches store to branch_to."""
169
raise NotImplementedError('push_stores is abstract')
171
def get_transaction(self):
172
"""Return the current active transaction.
174
If no transaction is active, this returns a passthrough object
175
for which all data is immediately flushed and no caching happens.
177
raise NotImplementedError('get_transaction is abstract')
179
def lock_write(self):
180
raise NotImplementedError('lock_write is abstract')
183
raise NotImplementedError('lock_read is abstract')
186
raise NotImplementedError('unlock is abstract')
188
def abspath(self, name):
189
"""Return absolute filename for something in the branch
191
XXX: Robert Collins 20051017 what is this used for? why is it a branch
192
method and not a tree method.
194
raise NotImplementedError('abspath is abstract')
196
def controlfilename(self, file_or_path):
197
"""Return location relative to branch."""
198
raise NotImplementedError('controlfilename is abstract')
200
def controlfile(self, file_or_path, mode='r'):
201
"""Open a control file for this branch.
203
There are two classes of file in the control directory: text
204
and binary. binary files are untranslated byte streams. Text
205
control files are stored with Unix newlines and in UTF-8, even
206
if the platform or locale defaults are different.
208
Controlfiles should almost never be opened in write mode but
209
rather should be atomically copied and replaced using atomicfile.
211
raise NotImplementedError('controlfile is abstract')
213
def put_controlfile(self, path, f, encode=True):
214
"""Write an entry as a controlfile.
216
:param path: The path to put the file, relative to the .bzr control
218
:param f: A file-like or string object whose contents should be copied.
219
:param encode: If true, encode the contents as utf-8
221
raise NotImplementedError('put_controlfile is abstract')
223
def put_controlfiles(self, files, encode=True):
224
"""Write several entries as controlfiles.
226
:param files: A list of [(path, file)] pairs, where the path is the directory
227
underneath the bzr control directory
228
:param encode: If true, encode the contents as utf-8
230
raise NotImplementedError('put_controlfiles is abstract')
232
def get_root_id(self):
233
"""Return the id of this branches root"""
234
raise NotImplementedError('get_root_id is abstract')
236
def set_root_id(self, file_id):
237
raise NotImplementedError('set_root_id is abstract')
239
def print_file(self, file, revision_id):
240
"""Print `file` to stdout."""
241
raise NotImplementedError('print_file is abstract')
243
def append_revision(self, *revision_ids):
244
raise NotImplementedError('append_revision is abstract')
246
def set_revision_history(self, rev_history):
247
raise NotImplementedError('set_revision_history is abstract')
249
def has_revision(self, revision_id):
250
"""True if this branch has a copy of the revision.
252
This does not necessarily imply the revision is merge
253
or on the mainline."""
254
raise NotImplementedError('has_revision is abstract')
256
def get_revision_xml(self, revision_id):
257
raise NotImplementedError('get_revision_xml is abstract')
259
def get_revision(self, revision_id):
260
"""Return the Revision object for a named revision"""
261
raise NotImplementedError('get_revision is abstract')
263
def get_revision_delta(self, revno):
264
"""Return the delta for one revision.
266
The delta is relative to its mainline predecessor, or the
267
empty tree for revision 1.
269
assert isinstance(revno, int)
270
rh = self.revision_history()
271
if not (1 <= revno <= len(rh)):
272
raise InvalidRevisionNumber(revno)
274
# revno is 1-based; list is 0-based
276
new_tree = self.revision_tree(rh[revno-1])
278
old_tree = EmptyTree()
280
old_tree = self.revision_tree(rh[revno-2])
282
return compare_trees(old_tree, new_tree)
284
def get_revision_sha1(self, revision_id):
285
"""Hash the stored value of a revision, and return it."""
286
raise NotImplementedError('get_revision_sha1 is abstract')
288
def get_ancestry(self, revision_id):
289
"""Return a list of revision-ids integrated by a revision.
291
This currently returns a list, but the ordering is not guaranteed:
294
raise NotImplementedError('get_ancestry is abstract')
296
def get_inventory(self, revision_id):
297
"""Get Inventory object by hash."""
298
raise NotImplementedError('get_inventory is abstract')
300
def get_inventory_xml(self, revision_id):
301
"""Get inventory XML as a file object."""
302
raise NotImplementedError('get_inventory_xml is abstract')
304
def get_inventory_sha1(self, revision_id):
305
"""Return the sha1 hash of the inventory entry."""
306
raise NotImplementedError('get_inventory_sha1 is abstract')
308
def get_revision_inventory(self, revision_id):
309
"""Return inventory of a past revision."""
310
raise NotImplementedError('get_revision_inventory is abstract')
312
def revision_history(self):
313
"""Return sequence of revision hashes on to this branch."""
314
raise NotImplementedError('revision_history is abstract')
317
"""Return current revision number for this branch.
319
That is equivalent to the number of revisions committed to
322
return len(self.revision_history())
324
def last_revision(self):
325
"""Return last patch hash, or None if no history."""
326
ph = self.revision_history()
332
def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
333
"""Return a list of new revisions that would perfectly fit.
335
If self and other have not diverged, return a list of the revisions
336
present in other, but missing from self.
338
>>> from bzrlib.commit import commit
339
>>> bzrlib.trace.silent = True
340
>>> br1 = ScratchBranch()
341
>>> br2 = ScratchBranch()
342
>>> br1.missing_revisions(br2)
344
>>> commit(br2, "lala!", rev_id="REVISION-ID-1")
345
>>> br1.missing_revisions(br2)
347
>>> br2.missing_revisions(br1)
349
>>> commit(br1, "lala!", rev_id="REVISION-ID-1")
350
>>> br1.missing_revisions(br2)
352
>>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
353
>>> br1.missing_revisions(br2)
355
>>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
356
>>> br1.missing_revisions(br2)
357
Traceback (most recent call last):
358
DivergedBranches: These branches have diverged. Try merge.
360
self_history = self.revision_history()
361
self_len = len(self_history)
362
other_history = other.revision_history()
363
other_len = len(other_history)
364
common_index = min(self_len, other_len) -1
365
if common_index >= 0 and \
366
self_history[common_index] != other_history[common_index]:
367
raise DivergedBranches(self, other)
369
if stop_revision is None:
370
stop_revision = other_len
372
assert isinstance(stop_revision, int)
373
if stop_revision > other_len:
374
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
375
return other_history[self_len:stop_revision]
377
def update_revisions(self, other, stop_revision=None):
378
"""Pull in new perfect-fit revisions."""
379
raise NotImplementedError('update_revisions is abstract')
381
def pullable_revisions(self, other, stop_revision):
382
raise NotImplementedError('pullable_revisions is abstract')
384
def revision_id_to_revno(self, revision_id):
385
"""Given a revision id, return its revno"""
386
if revision_id is None:
388
history = self.revision_history()
390
return history.index(revision_id) + 1
392
raise bzrlib.errors.NoSuchRevision(self, revision_id)
394
def get_rev_id(self, revno, history=None):
395
"""Find the revision id of the specified revno."""
399
history = self.revision_history()
400
elif revno <= 0 or revno > len(history):
401
raise bzrlib.errors.NoSuchRevision(self, revno)
402
return history[revno - 1]
404
def revision_tree(self, revision_id):
405
"""Return Tree for a revision on this branch.
407
`revision_id` may be None for the null revision, in which case
408
an `EmptyTree` is returned."""
409
raise NotImplementedError('revision_tree is abstract')
411
def working_tree(self):
412
"""Return a `Tree` for the working copy if this is a local branch."""
413
raise NotImplementedError('working_tree is abstract')
415
def pull(self, source, overwrite=False):
416
raise NotImplementedError('pull is abstract')
418
def basis_tree(self):
419
"""Return `Tree` object for last revision.
421
If there are no revisions yet, return an `EmptyTree`.
423
return self.revision_tree(self.last_revision())
425
def rename_one(self, from_rel, to_rel):
428
This can change the directory or the filename or both.
430
raise NotImplementedError('rename_one is abstract')
432
def move(self, from_paths, to_name):
435
to_name must exist as a versioned directory.
437
If to_name exists and is a directory, the files are moved into
438
it, keeping their old names. If it is a directory,
440
Note that to_name is only the last component of the new name;
441
this doesn't change the directory.
443
This returns a list of (from_path, to_path) pairs for each
446
raise NotImplementedError('move is abstract')
448
def get_parent(self):
449
"""Return the parent location of the branch.
451
This is the default location for push/pull/missing. The usual
452
pattern is that the user can override it by specifying a
455
raise NotImplementedError('get_parent is abstract')
457
def get_push_location(self):
458
"""Return the None or the location to push this branch to."""
459
raise NotImplementedError('get_push_location is abstract')
461
def set_push_location(self, location):
462
"""Set a new push location for this branch."""
463
raise NotImplementedError('set_push_location is abstract')
465
def set_parent(self, url):
466
raise NotImplementedError('set_parent is abstract')
468
def check_revno(self, revno):
470
Check whether a revno corresponds to any revision.
471
Zero (the NULL revision) is considered valid.
474
self.check_real_revno(revno)
476
def check_real_revno(self, revno):
478
Check whether a revno corresponds to a real revision.
479
Zero (the NULL revision) is considered invalid
481
if revno < 1 or revno > self.revno():
482
raise InvalidRevisionNumber(revno)
484
def sign_revision(self, revision_id, gpg_strategy):
485
raise NotImplementedError('sign_revision is abstract')
487
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
488
raise NotImplementedError('store_revision_signature is abstract')
490
class BzrBranch(Branch):
156
491
"""A branch stored in the actual filesystem.
158
493
Note that it's "local" in the context of the filesystem; it doesn't
513
817
'or remove the .bzr directory'
514
818
' and "bzr init" again'])
516
821
def get_root_id(self):
517
"""Return the id of this branches root"""
518
inv = self.read_working_inventory()
822
"""See Branch.get_root_id."""
823
inv = self.get_inventory(self.last_revision())
519
824
return inv.root.file_id
521
def set_root_id(self, file_id):
522
inv = self.read_working_inventory()
523
orig_root_id = inv.root.file_id
524
del inv._byid[inv.root.file_id]
525
inv.root.file_id = file_id
526
inv._byid[inv.root.file_id] = inv.root
529
if entry.parent_id in (None, orig_root_id):
530
entry.parent_id = inv.root.file_id
531
self._write_inventory(inv)
534
def read_working_inventory(self):
535
"""Read the working inventory."""
536
# ElementTree does its own conversion from UTF-8, so open in
538
f = self.controlfile('inventory', 'rb')
539
return bzrlib.xml5.serializer_v5.read_inventory(f)
542
def _write_inventory(self, inv):
543
"""Update the working inventory.
545
That is to say, the inventory describing changes underway, that
546
will be committed to the next revision.
548
from cStringIO import StringIO
550
bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
552
# Transport handles atomicity
553
self.put_controlfile('inventory', sio)
555
mutter('wrote working inventory')
557
inventory = property(read_working_inventory, _write_inventory, None,
558
"""Inventory for the working copy.""")
561
def add(self, files, ids=None):
562
"""Make files versioned.
564
Note that the command line normally calls smart_add instead,
565
which can automatically recurse.
567
This puts the files in the Added state, so that they will be
568
recorded by the next commit.
571
List of paths to add, relative to the base of the tree.
574
If set, use these instead of automatically generated ids.
575
Must be the same length as the list of files, but may
576
contain None for ids that are to be autogenerated.
578
TODO: Perhaps have an option to add the ids even if the files do
581
TODO: Perhaps yield the ids and paths as they're added.
583
# TODO: Re-adding a file that is removed in the working copy
584
# should probably put it back with the previous ID.
585
if isinstance(files, basestring):
586
assert(ids is None or isinstance(ids, basestring))
592
ids = [None] * len(files)
594
assert(len(ids) == len(files))
596
inv = self.read_working_inventory()
597
for f,file_id in zip(files, ids):
598
if is_control_file(f):
599
raise BzrError("cannot add control file %s" % quotefn(f))
604
raise BzrError("cannot add top-level %r" % f)
606
fullpath = os.path.normpath(self.abspath(f))
609
kind = file_kind(fullpath)
611
# maybe something better?
612
raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
614
if not InventoryEntry.versionable_kind(kind):
615
raise BzrError('cannot add: not a versionable file ('
616
'i.e. regular file, symlink or directory): %s' % quotefn(f))
619
file_id = gen_file_id(f)
620
inv.add_path(f, kind=kind, file_id=file_id)
622
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
624
self._write_inventory(inv)
627
def print_file(self, file, revno):
628
"""Print `file` to stdout."""
629
tree = self.revision_tree(self.get_rev_id(revno))
827
def print_file(self, file, revision_id):
828
"""See Branch.print_file."""
829
tree = self.revision_tree(revision_id)
630
830
# use inventory as it was in that revision
631
831
file_id = tree.inventory.path2id(file)
633
raise BzrError("%r is not present in revision %s" % (file, revno))
834
revno = self.revision_id_to_revno(revision_id)
835
except errors.NoSuchRevision:
836
# TODO: This should not be BzrError,
837
# but NoSuchFile doesn't fit either
838
raise BzrError('%r is not present in revision %s'
839
% (file, revision_id))
841
raise BzrError('%r is not present in revision %s'
634
843
tree.print_file(file_id)
636
# FIXME: this doesn't need to be a branch method
637
def set_inventory(self, new_inventory_list):
638
from bzrlib.inventory import Inventory, InventoryEntry
639
inv = Inventory(self.get_root_id())
640
for path, file_id, parent, kind in new_inventory_list:
641
name = os.path.basename(path)
644
# fixme, there should be a factory function inv,add_??
645
if kind == 'directory':
646
inv.add(inventory.InventoryDirectory(file_id, name, parent))
648
inv.add(inventory.InventoryFile(file_id, name, parent))
649
elif kind == 'symlink':
650
inv.add(inventory.InventoryLink(file_id, name, parent))
652
raise BzrError("unknown kind %r" % kind)
653
self._write_inventory(inv)
656
"""Return all unknown files.
658
These are files in the working directory that are not versioned or
659
control files or ignored.
661
>>> from bzrlib.workingtree import WorkingTree
662
>>> b = ScratchBranch(files=['foo', 'foo~'])
663
>>> map(str, b.unknowns())
666
>>> list(b.unknowns())
668
>>> WorkingTree(b.base, b).remove('foo')
669
>>> list(b.unknowns())
672
return self.working_tree().unknowns()
674
845
@needs_write_lock
675
846
def append_revision(self, *revision_ids):
847
"""See Branch.append_revision."""
676
848
for revision_id in revision_ids:
677
849
mutter("add {%s} to revision-history" % revision_id)
678
850
rev_history = self.revision_history()
679
851
rev_history.extend(revision_ids)
852
self.set_revision_history(rev_history)
855
def set_revision_history(self, rev_history):
856
"""See Branch.set_revision_history."""
857
old_revision = self.last_revision()
858
new_revision = rev_history[-1]
680
859
self.put_controlfile('revision-history', '\n'.join(rev_history))
861
self.working_tree().set_last_revision(new_revision, old_revision)
862
except NoWorkingTree:
863
mutter('Unable to set_last_revision without a working tree.')
682
865
def has_revision(self, revision_id):
683
"""True if this branch has a copy of the revision.
685
This does not necessarily imply the revision is merge
686
or on the mainline."""
866
"""See Branch.has_revision."""
687
867
return (revision_id is None
688
868
or self.revision_store.has_id(revision_id))
691
def get_revision_xml_file(self, revision_id):
692
"""Return XML file object for revision object."""
871
def _get_revision_xml_file(self, revision_id):
693
872
if not revision_id or not isinstance(revision_id, basestring):
694
raise InvalidRevisionId(revision_id)
873
raise InvalidRevisionId(revision_id=revision_id, branch=self)
696
875
return self.revision_store.get(revision_id)
697
876
except (IndexError, KeyError):
698
877
raise bzrlib.errors.NoSuchRevision(self, revision_id)
701
get_revision_xml = get_revision_xml_file
703
879
def get_revision_xml(self, revision_id):
704
return self.get_revision_xml_file(revision_id).read()
880
"""See Branch.get_revision_xml."""
881
return self._get_revision_xml_file(revision_id).read()
707
883
def get_revision(self, revision_id):
708
"""Return the Revision object for a named revision"""
709
xml_file = self.get_revision_xml_file(revision_id)
884
"""See Branch.get_revision."""
885
xml_file = self._get_revision_xml_file(revision_id)
712
888
r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
750
905
return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
752
907
def get_ancestry(self, revision_id):
753
"""Return a list of revision-ids integrated by a revision.
755
This currently returns a list, but the ordering is not guaranteed:
908
"""See Branch.get_ancestry."""
758
909
if revision_id is None:
760
w = self.get_inventory_weave()
911
w = self._get_inventory_weave()
761
912
return [None] + map(w.idx_to_name,
762
913
w.inclusions([w.lookup(revision_id)]))
764
def get_inventory_weave(self):
915
def _get_inventory_weave(self):
765
916
return self.control_weaves.get_weave('inventory',
766
917
self.get_transaction())
768
919
def get_inventory(self, revision_id):
769
"""Get Inventory object by hash."""
920
"""See Branch.get_inventory."""
770
921
xml = self.get_inventory_xml(revision_id)
771
922
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
773
924
def get_inventory_xml(self, revision_id):
774
"""Get inventory XML as a file object."""
925
"""See Branch.get_inventory_xml."""
776
927
assert isinstance(revision_id, basestring), type(revision_id)
777
iw = self.get_inventory_weave()
928
iw = self._get_inventory_weave()
778
929
return iw.get_text(iw.lookup(revision_id))
779
930
except IndexError:
780
931
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
782
933
def get_inventory_sha1(self, revision_id):
783
"""Return the sha1 hash of the inventory entry
934
"""See Branch.get_inventory_sha1."""
785
935
return self.get_revision(revision_id).inventory_sha1
787
937
def get_revision_inventory(self, revision_id):
788
"""Return inventory of a past revision."""
938
"""See Branch.get_revision_inventory."""
789
939
# TODO: Unify this with get_inventory()
790
940
# bzr 0.0.6 and later imposes the constraint that the inventory_id
791
941
# must be the same as its revision, so this is trivial.
792
942
if revision_id == None:
793
return Inventory(self.get_root_id())
943
# This does not make sense: if there is no revision,
944
# then it is the current tree inventory surely ?!
945
# and thus get_root_id() is something that looks at the last
946
# commit on the branch, and the get_root_id is an inventory check.
947
raise NotImplementedError
948
# return Inventory(self.get_root_id())
795
950
return self.get_inventory(revision_id)
798
953
def revision_history(self):
799
"""Return sequence of revision hashes on to this branch."""
954
"""See Branch.revision_history."""
800
955
transaction = self.get_transaction()
801
956
history = transaction.map.find_revision_history()
802
957
if history is not None:
810
965
# transaction.register_clean(history, precious=True)
811
966
return list(history)
814
"""Return current revision number for this branch.
816
That is equivalent to the number of revisions committed to
819
return len(self.revision_history())
821
def last_revision(self):
822
"""Return last patch hash, or None if no history.
824
ph = self.revision_history()
830
def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
831
"""Return a list of new revisions that would perfectly fit.
833
If self and other have not diverged, return a list of the revisions
834
present in other, but missing from self.
836
>>> from bzrlib.commit import commit
837
>>> bzrlib.trace.silent = True
838
>>> br1 = ScratchBranch()
839
>>> br2 = ScratchBranch()
840
>>> br1.missing_revisions(br2)
842
>>> commit(br2, "lala!", rev_id="REVISION-ID-1")
843
>>> br1.missing_revisions(br2)
845
>>> br2.missing_revisions(br1)
847
>>> commit(br1, "lala!", rev_id="REVISION-ID-1")
848
>>> br1.missing_revisions(br2)
850
>>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
851
>>> br1.missing_revisions(br2)
853
>>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
854
>>> br1.missing_revisions(br2)
855
Traceback (most recent call last):
856
DivergedBranches: These branches have diverged.
858
self_history = self.revision_history()
859
self_len = len(self_history)
860
other_history = other.revision_history()
861
other_len = len(other_history)
862
common_index = min(self_len, other_len) -1
863
if common_index >= 0 and \
864
self_history[common_index] != other_history[common_index]:
865
raise DivergedBranches(self, other)
867
if stop_revision is None:
868
stop_revision = other_len
870
assert isinstance(stop_revision, int)
871
if stop_revision > other_len:
872
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
873
return other_history[self_len:stop_revision]
875
968
def update_revisions(self, other, stop_revision=None):
876
"""Pull in new perfect-fit revisions."""
877
# FIXME: If the branches have diverged, but the latest
878
# revision in this branch is completely merged into the other,
879
# then we should still be able to pull.
969
"""See Branch.update_revisions."""
880
970
from bzrlib.fetch import greedy_fetch
881
971
if stop_revision is None:
882
972
stop_revision = other.last_revision()
909
def commit(self, *args, **kw):
910
from bzrlib.commit import Commit
911
Commit().commit(self, *args, **kw)
913
def revision_id_to_revno(self, revision_id):
914
"""Given a revision id, return its revno"""
915
if revision_id is None:
917
history = self.revision_history()
919
return history.index(revision_id) + 1
921
raise bzrlib.errors.NoSuchRevision(self, revision_id)
923
def get_rev_id(self, revno, history=None):
924
"""Find the revision id of the specified revno."""
928
history = self.revision_history()
929
elif revno <= 0 or revno > len(history):
930
raise bzrlib.errors.NoSuchRevision(self, revno)
931
return history[revno - 1]
933
1000
def revision_tree(self, revision_id):
934
"""Return Tree for a revision on this branch.
936
`revision_id` may be None for the null revision, in which case
937
an `EmptyTree` is returned."""
1001
"""See Branch.revision_tree."""
938
1002
# TODO: refactor this to use an existing revision object
939
1003
# so we don't need to read it in twice.
940
if revision_id == None:
1004
if revision_id == None or revision_id == NULL_REVISION:
941
1005
return EmptyTree()
943
1007
inv = self.get_revision_inventory(revision_id)
944
1008
return RevisionTree(self.weave_store, inv, revision_id)
1010
def basis_tree(self):
1011
"""See Branch.basis_tree."""
1013
revision_id = self.revision_history()[-1]
1014
xml = self.working_tree().read_basis_inventory(revision_id)
1015
inv = bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
1016
return RevisionTree(self.weave_store, inv, revision_id)
1017
except (IndexError, NoSuchFile, NoWorkingTree), e:
1018
return self.revision_tree(self.last_revision())
946
1020
def working_tree(self):
947
"""Return a `Tree` for the working copy."""
1021
"""See Branch.working_tree."""
948
1022
from bzrlib.workingtree import WorkingTree
949
# TODO: In the future, perhaps WorkingTree should utilize Transport
950
# RobertCollins 20051003 - I don't think it should - working trees are
951
# much more complex to keep consistent than our careful .bzr subset.
952
# instead, we should say that working trees are local only, and optimise
1023
if self._transport.base.find('://') != -1:
1024
raise NoWorkingTree(self.base)
954
1025
return WorkingTree(self.base, branch=self)
957
def basis_tree(self):
958
"""Return `Tree` object for last revision.
960
If there are no revisions yet, return an `EmptyTree`.
962
return self.revision_tree(self.last_revision())
964
1027
@needs_write_lock
965
def rename_one(self, from_rel, to_rel):
968
This can change the directory or the filename or both.
970
tree = self.working_tree()
972
if not tree.has_filename(from_rel):
973
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
974
if tree.has_filename(to_rel):
975
raise BzrError("can't rename: new working file %r already exists" % to_rel)
977
file_id = inv.path2id(from_rel)
979
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
981
if inv.path2id(to_rel):
982
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
984
to_dir, to_tail = os.path.split(to_rel)
985
to_dir_id = inv.path2id(to_dir)
986
if to_dir_id == None and to_dir != '':
987
raise BzrError("can't determine destination directory id for %r" % to_dir)
989
mutter("rename_one:")
990
mutter(" file_id {%s}" % file_id)
991
mutter(" from_rel %r" % from_rel)
992
mutter(" to_rel %r" % to_rel)
993
mutter(" to_dir %r" % to_dir)
994
mutter(" to_dir_id {%s}" % to_dir_id)
996
inv.rename(file_id, to_dir_id, to_tail)
998
from_abs = self.abspath(from_rel)
999
to_abs = self.abspath(to_rel)
1028
def pull(self, source, overwrite=False):
1029
"""See Branch.pull."""
1001
rename(from_abs, to_abs)
1003
raise BzrError("failed to rename %r to %r: %s"
1004
% (from_abs, to_abs, e[1]),
1005
["rename rolled back"])
1007
self._write_inventory(inv)
1010
def move(self, from_paths, to_name):
1013
to_name must exist as a versioned directory.
1015
If to_name exists and is a directory, the files are moved into
1016
it, keeping their old names. If it is a directory,
1018
Note that to_name is only the last component of the new name;
1019
this doesn't change the directory.
1021
This returns a list of (from_path, to_path) pairs for each
1022
entry that is moved.
1025
## TODO: Option to move IDs only
1026
assert not isinstance(from_paths, basestring)
1027
tree = self.working_tree()
1028
inv = tree.inventory
1029
to_abs = self.abspath(to_name)
1030
if not isdir(to_abs):
1031
raise BzrError("destination %r is not a directory" % to_abs)
1032
if not tree.has_filename(to_name):
1033
raise BzrError("destination %r not in working directory" % to_abs)
1034
to_dir_id = inv.path2id(to_name)
1035
if to_dir_id == None and to_name != '':
1036
raise BzrError("destination %r is not a versioned directory" % to_name)
1037
to_dir_ie = inv[to_dir_id]
1038
if to_dir_ie.kind not in ('directory', 'root_directory'):
1039
raise BzrError("destination %r is not a directory" % to_abs)
1041
to_idpath = inv.get_idpath(to_dir_id)
1043
for f in from_paths:
1044
if not tree.has_filename(f):
1045
raise BzrError("%r does not exist in working tree" % f)
1046
f_id = inv.path2id(f)
1048
raise BzrError("%r is not versioned" % f)
1049
name_tail = splitpath(f)[-1]
1050
dest_path = appendpath(to_name, name_tail)
1051
if tree.has_filename(dest_path):
1052
raise BzrError("destination %r already exists" % dest_path)
1053
if f_id in to_idpath:
1054
raise BzrError("can't move %r to a subdirectory of itself" % f)
1056
# OK, so there's a race here, it's possible that someone will
1057
# create a file in this interval and then the rename might be
1058
# left half-done. But we should have caught most problems.
1060
for f in from_paths:
1061
name_tail = splitpath(f)[-1]
1062
dest_path = appendpath(to_name, name_tail)
1063
result.append((f, dest_path))
1064
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1066
rename(self.abspath(f), self.abspath(dest_path))
1068
raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1069
["rename rolled back"])
1071
self._write_inventory(inv)
1075
def revert(self, filenames, old_tree=None, backups=True):
1076
"""Restore selected files to the versions from a previous tree.
1079
If true (default) backups are made of files before
1082
from bzrlib.atomicfile import AtomicFile
1083
from bzrlib.osutils import backup_file
1085
inv = self.read_working_inventory()
1086
if old_tree is None:
1087
old_tree = self.basis_tree()
1088
old_inv = old_tree.inventory
1091
for fn in filenames:
1092
file_id = inv.path2id(fn)
1094
raise NotVersionedError(path=fn)
1095
if not old_inv.has_id(file_id):
1096
raise BzrError("file not present in old tree", fn, file_id)
1097
nids.append((fn, file_id))
1099
# TODO: Rename back if it was previously at a different location
1101
# TODO: If given a directory, restore the entire contents from
1102
# the previous version.
1104
# TODO: Make a backup to a temporary file.
1106
# TODO: If the file previously didn't exist, delete it?
1107
for fn, file_id in nids:
1110
f = AtomicFile(fn, 'wb')
1112
f.write(old_tree.get_file(file_id).read())
1118
def pending_merges(self):
1119
"""Return a list of pending merges.
1121
These are revisions that have been merged into the working
1122
directory but not yet committed.
1124
cfn = self._rel_controlfilename('pending-merges')
1125
if not self._transport.has(cfn):
1128
for l in self.controlfile('pending-merges', 'r').readlines():
1129
p.append(l.rstrip('\n'))
1133
def add_pending_merge(self, *revision_ids):
1134
# TODO: Perhaps should check at this point that the
1135
# history of the revision is actually present?
1136
p = self.pending_merges()
1138
for rev_id in revision_ids:
1144
self.set_pending_merges(p)
1147
def set_pending_merges(self, rev_list):
1148
self.put_controlfile('pending-merges', '\n'.join(rev_list))
1032
old_count = len(self.revision_history())
1034
self.update_revisions(source)
1035
except DivergedBranches:
1039
self.set_revision_history(source.revision_history())
1040
new_count = len(self.revision_history())
1041
return new_count - old_count
1150
1045
def get_parent(self):
1151
"""Return the parent location of the branch.
1153
This is the default location for push/pull/missing. The usual
1154
pattern is that the user can override it by specifying a
1046
"""See Branch.get_parent."""
1158
1048
_locs = ['parent', 'pull', 'x-pull']
1159
1049
for l in _locs:
1161
1051
return self.controlfile(l, 'r').read().strip('\n')
1163
if e.errno != errno.ENOENT:
1056
def get_push_location(self):
1057
"""See Branch.get_push_location."""
1058
config = bzrlib.config.BranchConfig(self)
1059
push_loc = config.get_user_option('push_location')
1062
def set_push_location(self, location):
1063
"""See Branch.set_push_location."""
1064
config = bzrlib.config.LocationConfig(self.base)
1065
config.set_user_option('push_location', location)
1167
1067
@needs_write_lock
1168
1068
def set_parent(self, url):
1069
"""See Branch.set_parent."""
1169
1070
# TODO: Maybe delete old location files?
1170
1071
from bzrlib.atomicfile import AtomicFile
1171
1072
f = AtomicFile(self.controlfilename('parent'))