/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Aaron Bentley
  • Date: 2005-09-14 16:35:46 UTC
  • mto: (1185.1.16)
  • mto: This revision was merged to the branch mainline in revision 1390.
  • Revision ID: abentley@panoramicfeedback.com-20050914163546-ef044baf4ef9c135
Improved merge error handling and testing

Show diffs side-by-side

added added

removed removed

Lines of Context:
23
23
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
24
24
     splitpath, \
25
25
     sha_file, appendpath, file_kind
 
26
 
26
27
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId
27
28
import bzrlib.errors
28
29
from bzrlib.textui import show_status
29
30
from bzrlib.revision import Revision
30
 
from bzrlib.xml import unpack_xml
31
31
from bzrlib.delta import compare_trees
32
32
from bzrlib.tree import EmptyTree, RevisionTree
33
 
        
 
33
import bzrlib.xml
 
34
import bzrlib.ui
 
35
 
 
36
 
 
37
 
34
38
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
35
39
## TODO: Maybe include checks for common corruption of newlines, etc?
36
40
 
39
43
# repeatedly to calculate deltas.  We could perhaps have a weakref
40
44
# cache in memory to make this faster.
41
45
 
 
46
# TODO: please move the revision-string syntax stuff out of the branch
 
47
# object; it's clutter
 
48
 
42
49
 
43
50
def find_branch(f, **args):
44
51
    if f and (f.startswith('http://') or f.startswith('https://')):
101
108
    It is not necessary that f exists.
102
109
 
103
110
    Basically we keep looking up until we find the control directory or
104
 
    run into the root."""
 
111
    run into the root.  If there isn't one, raises NotBranchError.
 
112
    """
105
113
    if f == None:
106
114
        f = os.getcwd()
107
115
    elif hasattr(os.path, 'realpath'):
120
128
        head, tail = os.path.split(f)
121
129
        if head == f:
122
130
            # reached the root, whatever that may be
123
 
            raise BzrError('%r is not in a branch' % orig_f)
 
131
            raise bzrlib.errors.NotBranchError('%s is not in a branch' % orig_f)
124
132
        f = head
125
 
    
 
133
 
 
134
 
 
135
 
 
136
# XXX: move into bzrlib.errors; subclass BzrError    
126
137
class DivergedBranches(Exception):
127
138
    def __init__(self, branch1, branch2):
128
139
        self.branch1 = branch1
208
219
            self._lock.unlock()
209
220
 
210
221
 
211
 
 
212
222
    def lock_write(self):
213
223
        if self._lock_mode:
214
224
            if self._lock_mode != 'w':
224
234
            self._lock_count = 1
225
235
 
226
236
 
227
 
 
228
237
    def lock_read(self):
229
238
        if self._lock_mode:
230
239
            assert self._lock_mode in ('r', 'w'), \
237
246
            self._lock_mode = 'r'
238
247
            self._lock_count = 1
239
248
                        
240
 
 
241
 
            
242
249
    def unlock(self):
243
250
        if not self._lock_mode:
244
251
            from errors import LockError
251
258
            self._lock = None
252
259
            self._lock_mode = self._lock_count = None
253
260
 
254
 
 
255
261
    def abspath(self, name):
256
262
        """Return absolute filename for something in the branch"""
257
263
        return os.path.join(self.base, name)
258
264
 
259
 
 
260
265
    def relpath(self, path):
261
266
        """Return path relative to this branch of something inside it.
262
267
 
263
268
        Raises an error if path is not in this branch."""
264
269
        return _relpath(self.base, path)
265
270
 
266
 
 
267
271
    def controlfilename(self, file_or_path):
268
272
        """Return location relative to branch."""
269
273
        if isinstance(file_or_path, basestring):
296
300
        else:
297
301
            raise BzrError("invalid controlfile mode %r" % mode)
298
302
 
299
 
 
300
 
 
301
303
    def _make_control(self):
302
304
        from bzrlib.inventory import Inventory
303
 
        from bzrlib.xml import pack_xml
304
305
        
305
306
        os.mkdir(self.controlfilename([]))
306
307
        self.controlfile('README', 'w').write(
316
317
            self.controlfile(f, 'w').write('')
317
318
        mutter('created control directory in ' + self.base)
318
319
 
319
 
        pack_xml(Inventory(gen_root_id()), self.controlfile('inventory','w'))
 
320
        # if we want per-tree root ids then this is the place to set
 
321
        # them; they're not needed for now and so ommitted for
 
322
        # simplicity.
 
323
        f = self.controlfile('inventory','w')
 
324
        bzrlib.xml.serializer_v4.write_inventory(Inventory(), f)
320
325
 
321
326
 
322
327
    def _check_format(self):
331
336
        # on Windows from Linux and so on.  I think it might be better
332
337
        # to always make all internal files in unix format.
333
338
        fmt = self.controlfile('branch-format', 'r').read()
334
 
        fmt.replace('\r\n', '')
 
339
        fmt = fmt.replace('\r\n', '\n')
335
340
        if fmt != BZR_BRANCH_FORMAT:
336
341
            raise BzrError('sorry, branch format %r not supported' % fmt,
337
342
                           ['use a different bzr version',
357
362
    def read_working_inventory(self):
358
363
        """Read the working inventory."""
359
364
        from bzrlib.inventory import Inventory
360
 
        from bzrlib.xml import unpack_xml
361
 
        from time import time
362
 
        before = time()
363
365
        self.lock_read()
364
366
        try:
365
367
            # ElementTree does its own conversion from UTF-8, so open in
366
368
            # binary.
367
 
            inv = unpack_xml(Inventory,
368
 
                             self.controlfile('inventory', 'rb'))
369
 
            mutter("loaded inventory of %d items in %f"
370
 
                   % (len(inv), time() - before))
371
 
            return inv
 
369
            f = self.controlfile('inventory', 'rb')
 
370
            return bzrlib.xml.serializer_v4.read_inventory(f)
372
371
        finally:
373
372
            self.unlock()
374
373
            
380
379
        will be committed to the next revision.
381
380
        """
382
381
        from bzrlib.atomicfile import AtomicFile
383
 
        from bzrlib.xml import pack_xml
384
382
        
385
383
        self.lock_write()
386
384
        try:
387
385
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
388
386
            try:
389
 
                pack_xml(inv, f)
 
387
                bzrlib.xml.serializer_v4.write_inventory(inv, f)
390
388
                f.commit()
391
389
            finally:
392
390
                f.close()
400
398
                         """Inventory for the working copy.""")
401
399
 
402
400
 
403
 
    def add(self, files, verbose=False, ids=None):
 
401
    def add(self, files, ids=None):
404
402
        """Make files versioned.
405
403
 
406
 
        Note that the command line normally calls smart_add instead.
 
404
        Note that the command line normally calls smart_add instead,
 
405
        which can automatically recurse.
407
406
 
408
407
        This puts the files in the Added state, so that they will be
409
408
        recorded by the next commit.
419
418
        TODO: Perhaps have an option to add the ids even if the files do
420
419
              not (yet) exist.
421
420
 
422
 
        TODO: Perhaps return the ids of the files?  But then again it
423
 
              is easy to retrieve them if they're needed.
424
 
 
425
 
        TODO: Adding a directory should optionally recurse down and
426
 
              add all non-ignored children.  Perhaps do that in a
427
 
              higher-level method.
 
421
        TODO: Perhaps yield the ids and paths as they're added.
428
422
        """
429
423
        # TODO: Re-adding a file that is removed in the working copy
430
424
        # should probably put it back with the previous ID.
466
460
                    file_id = gen_file_id(f)
467
461
                inv.add_path(f, kind=kind, file_id=file_id)
468
462
 
469
 
                if verbose:
470
 
                    print 'added', quotefn(f)
471
 
 
472
463
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
473
464
 
474
465
            self._write_inventory(inv)
584
575
            f.close()
585
576
 
586
577
 
587
 
    def get_revision_xml(self, revision_id):
 
578
    def get_revision_xml_file(self, revision_id):
588
579
        """Return XML file object for revision object."""
589
580
        if not revision_id or not isinstance(revision_id, basestring):
590
581
            raise InvalidRevisionId(revision_id)
593
584
        try:
594
585
            try:
595
586
                return self.revision_store[revision_id]
596
 
            except IndexError:
597
 
                raise bzrlib.errors.NoSuchRevision(revision_id)
 
587
            except KeyError:
 
588
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
598
589
        finally:
599
590
            self.unlock()
600
591
 
601
592
 
 
593
    #deprecated
 
594
    get_revision_xml = get_revision_xml_file
 
595
 
 
596
 
602
597
    def get_revision(self, revision_id):
603
598
        """Return the Revision object for a named revision"""
604
 
        xml_file = self.get_revision_xml(revision_id)
 
599
        xml_file = self.get_revision_xml_file(revision_id)
605
600
 
606
601
        try:
607
 
            r = unpack_xml(Revision, xml_file)
 
602
            r = bzrlib.xml.serializer_v4.read_revision(xml_file)
608
603
        except SyntaxError, e:
609
604
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
610
605
                                         [revision_id,
655
650
               parameter which can be either an integer revno or a
656
651
               string hash."""
657
652
        from bzrlib.inventory import Inventory
658
 
        from bzrlib.xml import unpack_xml
659
 
 
660
 
        return unpack_xml(Inventory, self.inventory_store[inventory_id])
 
653
 
 
654
        f = self.get_inventory_xml_file(inventory_id)
 
655
        return bzrlib.xml.serializer_v4.read_inventory(f)
 
656
 
 
657
 
 
658
    def get_inventory_xml(self, inventory_id):
 
659
        """Get inventory XML as a file object."""
 
660
        return self.inventory_store[inventory_id]
 
661
 
 
662
    get_inventory_xml_file = get_inventory_xml
661
663
            
662
664
 
663
665
    def get_inventory_sha1(self, inventory_id):
664
666
        """Return the sha1 hash of the inventory entry
665
667
        """
666
 
        return sha_file(self.inventory_store[inventory_id])
 
668
        return sha_file(self.get_inventory_xml(inventory_id))
667
669
 
668
670
 
669
671
    def get_revision_inventory(self, revision_id):
755
757
            return None
756
758
 
757
759
 
758
 
    def missing_revisions(self, other, stop_revision=None):
 
760
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
759
761
        """
760
762
        If self and other have not diverged, return a list of the revisions
761
763
        present in other, but missing from self.
794
796
        if stop_revision is None:
795
797
            stop_revision = other_len
796
798
        elif stop_revision > other_len:
797
 
            raise NoSuchRevision(self, stop_revision)
 
799
            raise bzrlib.errors.NoSuchRevision(self, stop_revision)
798
800
        
799
801
        return other_history[self_len:stop_revision]
800
802
 
801
803
 
802
804
    def update_revisions(self, other, stop_revision=None):
803
805
        """Pull in all new revisions from other branch.
804
 
        
805
 
        >>> from bzrlib.commit import commit
806
 
        >>> bzrlib.trace.silent = True
807
 
        >>> br1 = ScratchBranch(files=['foo', 'bar'])
808
 
        >>> br1.add('foo')
809
 
        >>> br1.add('bar')
810
 
        >>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
811
 
        >>> br2 = ScratchBranch()
812
 
        >>> br2.update_revisions(br1)
813
 
        Added 2 texts.
814
 
        Added 1 inventories.
815
 
        Added 1 revisions.
816
 
        >>> br2.revision_history()
817
 
        [u'REVISION-ID-1']
818
 
        >>> br2.update_revisions(br1)
819
 
        Added 0 texts.
820
 
        Added 0 inventories.
821
 
        Added 0 revisions.
822
 
        >>> br1.text_store.total_size() == br2.text_store.total_size()
823
 
        True
824
806
        """
825
 
        from bzrlib.progress import ProgressBar
826
 
 
827
 
        pb = ProgressBar()
828
 
 
 
807
        from bzrlib.fetch import greedy_fetch
 
808
        from bzrlib.revision import get_intervening_revisions
 
809
 
 
810
        pb = bzrlib.ui.ui_factory.progress_bar()
829
811
        pb.update('comparing histories')
830
 
        revision_ids = self.missing_revisions(other, stop_revision)
831
 
 
 
812
        if stop_revision is None:
 
813
            other_revision = other.last_patch()
 
814
        else:
 
815
            other_revision = other.lookup_revision(stop_revision)
 
816
        count = greedy_fetch(self, other, other_revision, pb)[0]
 
817
        try:
 
818
            revision_ids = self.missing_revisions(other, stop_revision)
 
819
        except DivergedBranches, e:
 
820
            try:
 
821
                revision_ids = get_intervening_revisions(self.last_patch(), 
 
822
                                                         other_revision, self)
 
823
                assert self.last_patch() not in revision_ids
 
824
            except bzrlib.errors.NotAncestor:
 
825
                raise e
 
826
 
 
827
        self.append_revision(*revision_ids)
 
828
        pb.clear()
 
829
 
 
830
    def install_revisions(self, other, revision_ids, pb):
832
831
        if hasattr(other.revision_store, "prefetch"):
833
832
            other.revision_store.prefetch(revision_ids)
834
833
        if hasattr(other.inventory_store, "prefetch"):
835
 
            inventory_ids = [other.get_revision(r).inventory_id
836
 
                             for r in revision_ids]
 
834
            inventory_ids = []
 
835
            for rev_id in revision_ids:
 
836
                try:
 
837
                    revision = other.get_revision(rev_id).inventory_id
 
838
                    inventory_ids.append(revision)
 
839
                except bzrlib.errors.NoSuchRevision:
 
840
                    pass
837
841
            other.inventory_store.prefetch(inventory_ids)
 
842
 
 
843
        if pb is None:
 
844
            pb = bzrlib.ui.ui_factory.progress_bar()
838
845
                
839
846
        revisions = []
840
847
        needed_texts = set()
841
848
        i = 0
842
 
        for rev_id in revision_ids:
843
 
            i += 1
844
 
            pb.update('fetching revision', i, len(revision_ids))
845
 
            rev = other.get_revision(rev_id)
 
849
 
 
850
        failures = set()
 
851
        for i, rev_id in enumerate(revision_ids):
 
852
            pb.update('fetching revision', i+1, len(revision_ids))
 
853
            try:
 
854
                rev = other.get_revision(rev_id)
 
855
            except bzrlib.errors.NoSuchRevision:
 
856
                failures.add(rev_id)
 
857
                continue
 
858
 
846
859
            revisions.append(rev)
847
860
            inv = other.get_inventory(str(rev.inventory_id))
848
861
            for key, entry in inv.iter_entries():
853
866
 
854
867
        pb.clear()
855
868
                    
856
 
        count = self.text_store.copy_multi(other.text_store, needed_texts)
857
 
        print "Added %d texts." % count 
 
869
        count, cp_fail = self.text_store.copy_multi(other.text_store, 
 
870
                                                    needed_texts)
 
871
        #print "Added %d texts." % count 
858
872
        inventory_ids = [ f.inventory_id for f in revisions ]
859
 
        count = self.inventory_store.copy_multi(other.inventory_store, 
860
 
                                                inventory_ids)
861
 
        print "Added %d inventories." % count 
 
873
        count, cp_fail = self.inventory_store.copy_multi(other.inventory_store, 
 
874
                                                         inventory_ids)
 
875
        #print "Added %d inventories." % count 
862
876
        revision_ids = [ f.revision_id for f in revisions]
863
 
        count = self.revision_store.copy_multi(other.revision_store, 
864
 
                                               revision_ids)
865
 
        for revision_id in revision_ids:
866
 
            self.append_revision(revision_id)
867
 
        print "Added %d revisions." % count
868
 
                    
869
 
        
 
877
 
 
878
        count, cp_fail = self.revision_store.copy_multi(other.revision_store, 
 
879
                                                          revision_ids,
 
880
                                                          permit_failure=True)
 
881
        assert len(cp_fail) == 0 
 
882
        return count, failures
 
883
       
 
884
 
870
885
    def commit(self, *args, **kw):
871
886
        from bzrlib.commit import commit
872
887
        commit(self, *args, **kw)
874
889
 
875
890
    def lookup_revision(self, revision):
876
891
        """Return the revision identifier for a given revision information."""
877
 
        revno, info = self.get_revision_info(revision)
 
892
        revno, info = self._get_revision_info(revision)
878
893
        return info
879
894
 
 
895
 
 
896
    def revision_id_to_revno(self, revision_id):
 
897
        """Given a revision id, return its revno"""
 
898
        history = self.revision_history()
 
899
        try:
 
900
            return history.index(revision_id) + 1
 
901
        except ValueError:
 
902
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
903
 
 
904
 
880
905
    def get_revision_info(self, revision):
881
906
        """Return (revno, revision id) for revision identifier.
882
907
 
885
910
        revision can also be a string, in which case it is parsed for something like
886
911
            'date:' or 'revid:' etc.
887
912
        """
 
913
        revno, rev_id = self._get_revision_info(revision)
 
914
        if revno is None:
 
915
            raise bzrlib.errors.NoSuchRevision(self, revision)
 
916
        return revno, rev_id
 
917
 
 
918
    def get_rev_id(self, revno, history=None):
 
919
        """Find the revision id of the specified revno."""
 
920
        if revno == 0:
 
921
            return None
 
922
        if history is None:
 
923
            history = self.revision_history()
 
924
        elif revno <= 0 or revno > len(history):
 
925
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
926
        return history[revno - 1]
 
927
 
 
928
    def _get_revision_info(self, revision):
 
929
        """Return (revno, revision id) for revision specifier.
 
930
 
 
931
        revision can be an integer, in which case it is assumed to be revno
 
932
        (though this will translate negative values into positive ones)
 
933
        revision can also be a string, in which case it is parsed for something
 
934
        like 'date:' or 'revid:' etc.
 
935
 
 
936
        A revid is always returned.  If it is None, the specifier referred to
 
937
        the null revision.  If the revid does not occur in the revision
 
938
        history, revno will be None.
 
939
        """
 
940
        
888
941
        if revision is None:
889
942
            return 0, None
890
943
        revno = None
894
947
            pass
895
948
        revs = self.revision_history()
896
949
        if isinstance(revision, int):
897
 
            if revision == 0:
898
 
                return 0, None
899
 
            # Mabye we should do this first, but we don't need it if revision == 0
900
950
            if revision < 0:
901
951
                revno = len(revs) + revision + 1
902
952
            else:
903
953
                revno = revision
 
954
            rev_id = self.get_rev_id(revno, revs)
904
955
        elif isinstance(revision, basestring):
905
956
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
906
957
                if revision.startswith(prefix):
907
 
                    revno = func(self, revs, revision)
 
958
                    result = func(self, revs, revision)
 
959
                    if len(result) > 1:
 
960
                        revno, rev_id = result
 
961
                    else:
 
962
                        revno = result[0]
 
963
                        rev_id = self.get_rev_id(revno, revs)
908
964
                    break
909
965
            else:
910
 
                raise BzrError('No namespace registered for string: %r' % revision)
 
966
                raise BzrError('No namespace registered for string: %r' %
 
967
                               revision)
 
968
        else:
 
969
            raise TypeError('Unhandled revision type %s' % revision)
911
970
 
912
 
        if revno is None or revno <= 0 or revno > len(revs):
913
 
            raise BzrError("no such revision %s" % revision)
914
 
        return revno, revs[revno-1]
 
971
        if revno is None:
 
972
            if rev_id is None:
 
973
                raise bzrlib.errors.NoSuchRevision(self, revision)
 
974
        return revno, rev_id
915
975
 
916
976
    def _namespace_revno(self, revs, revision):
917
977
        """Lookup a revision by revision number"""
918
978
        assert revision.startswith('revno:')
919
979
        try:
920
 
            return int(revision[6:])
 
980
            return (int(revision[6:]),)
921
981
        except ValueError:
922
982
            return None
923
983
    REVISION_NAMESPACES['revno:'] = _namespace_revno
924
984
 
925
985
    def _namespace_revid(self, revs, revision):
926
986
        assert revision.startswith('revid:')
 
987
        rev_id = revision[len('revid:'):]
927
988
        try:
928
 
            return revs.index(revision[6:]) + 1
 
989
            return revs.index(rev_id) + 1, rev_id
929
990
        except ValueError:
930
 
            return None
 
991
            return None, rev_id
931
992
    REVISION_NAMESPACES['revid:'] = _namespace_revid
932
993
 
933
994
    def _namespace_last(self, revs, revision):
935
996
        try:
936
997
            offset = int(revision[5:])
937
998
        except ValueError:
938
 
            return None
 
999
            return (None,)
939
1000
        else:
940
1001
            if offset <= 0:
941
1002
                raise BzrError('You must supply a positive value for --revision last:XXX')
942
 
            return len(revs) - offset + 1
 
1003
            return (len(revs) - offset + 1,)
943
1004
    REVISION_NAMESPACES['last:'] = _namespace_last
944
1005
 
945
1006
    def _namespace_tag(self, revs, revision):
1020
1081
                # TODO: Handle timezone.
1021
1082
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1022
1083
                if first >= dt and (last is None or dt >= last):
1023
 
                    return i+1
 
1084
                    return (i+1,)
1024
1085
        else:
1025
1086
            for i in range(len(revs)):
1026
1087
                r = self.get_revision(revs[i])
1027
1088
                # TODO: Handle timezone.
1028
1089
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1029
1090
                if first <= dt and (last is None or dt <= last):
1030
 
                    return i+1
 
1091
                    return (i+1,)
1031
1092
    REVISION_NAMESPACES['date:'] = _namespace_date
1032
1093
 
1033
1094
    def revision_tree(self, revision_id):
1098
1159
 
1099
1160
            inv.rename(file_id, to_dir_id, to_tail)
1100
1161
 
1101
 
            print "%s => %s" % (from_rel, to_rel)
1102
 
 
1103
1162
            from_abs = self.abspath(from_rel)
1104
1163
            to_abs = self.abspath(to_rel)
1105
1164
            try:
1124
1183
 
1125
1184
        Note that to_name is only the last component of the new name;
1126
1185
        this doesn't change the directory.
 
1186
 
 
1187
        This returns a list of (from_path, to_path) pairs for each
 
1188
        entry that is moved.
1127
1189
        """
 
1190
        result = []
1128
1191
        self.lock_write()
1129
1192
        try:
1130
1193
            ## TODO: Option to move IDs only
1165
1228
            for f in from_paths:
1166
1229
                name_tail = splitpath(f)[-1]
1167
1230
                dest_path = appendpath(to_name, name_tail)
1168
 
                print "%s => %s" % (f, dest_path)
 
1231
                result.append((f, dest_path))
1169
1232
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1170
1233
                try:
1171
1234
                    os.rename(self.abspath(f), self.abspath(dest_path))
1177
1240
        finally:
1178
1241
            self.unlock()
1179
1242
 
 
1243
        return result
 
1244
 
1180
1245
 
1181
1246
    def revert(self, filenames, old_tree=None, backups=True):
1182
1247
        """Restore selected files to the versions from a previous tree.
1264
1329
            self.unlock()
1265
1330
 
1266
1331
 
 
1332
    def get_parent(self):
 
1333
        """Return the parent location of the branch.
 
1334
 
 
1335
        This is the default location for push/pull/missing.  The usual
 
1336
        pattern is that the user can override it by specifying a
 
1337
        location.
 
1338
        """
 
1339
        import errno
 
1340
        _locs = ['parent', 'pull', 'x-pull']
 
1341
        for l in _locs:
 
1342
            try:
 
1343
                return self.controlfile(l, 'r').read().strip('\n')
 
1344
            except IOError, e:
 
1345
                if e.errno != errno.ENOENT:
 
1346
                    raise
 
1347
        return None
 
1348
 
 
1349
 
 
1350
    def set_parent(self, url):
 
1351
        # TODO: Maybe delete old location files?
 
1352
        from bzrlib.atomicfile import AtomicFile
 
1353
        self.lock_write()
 
1354
        try:
 
1355
            f = AtomicFile(self.controlfilename('parent'))
 
1356
            try:
 
1357
                f.write(url + '\n')
 
1358
                f.commit()
 
1359
            finally:
 
1360
                f.close()
 
1361
        finally:
 
1362
            self.unlock()
 
1363
 
 
1364
    def check_revno(self, revno):
 
1365
        """\
 
1366
        Check whether a revno corresponds to any revision.
 
1367
        Zero (the NULL revision) is considered valid.
 
1368
        """
 
1369
        if revno != 0:
 
1370
            self.check_real_revno(revno)
 
1371
            
 
1372
    def check_real_revno(self, revno):
 
1373
        """\
 
1374
        Check whether a revno corresponds to a real revision.
 
1375
        Zero (the NULL revision) is considered invalid
 
1376
        """
 
1377
        if revno < 1 or revno > self.revno():
 
1378
            raise InvalidRevisionNumber(revno)
 
1379
        
 
1380
        
 
1381
 
1267
1382
 
1268
1383
class ScratchBranch(Branch):
1269
1384
    """Special test class: a branch that cleans up after itself.
1311
1426
        os.rmdir(base)
1312
1427
        copytree(self.base, base, symlinks=True)
1313
1428
        return ScratchBranch(base=base)
 
1429
 
 
1430
 
1314
1431
        
1315
1432
    def __del__(self):
1316
1433
        self.destroy()
1386
1503
    """Return a new tree-root file id."""
1387
1504
    return gen_file_id('TREE_ROOT')
1388
1505
 
 
1506
 
 
1507
def pull_loc(branch):
 
1508
    # TODO: Should perhaps just make attribute be 'base' in
 
1509
    # RemoteBranch and Branch?
 
1510
    if hasattr(branch, "baseurl"):
 
1511
        return branch.baseurl
 
1512
    else:
 
1513
        return branch.base
 
1514
 
 
1515
 
 
1516
def copy_branch(branch_from, to_location, revision=None):
 
1517
    """Copy branch_from into the existing directory to_location.
 
1518
 
 
1519
    revision
 
1520
        If not None, only revisions up to this point will be copied.
 
1521
        The head of the new branch will be that revision.
 
1522
 
 
1523
    to_location
 
1524
        The name of a local directory that exists but is empty.
 
1525
    """
 
1526
    from bzrlib.merge import merge
 
1527
    from bzrlib.branch import Branch
 
1528
 
 
1529
    assert isinstance(branch_from, Branch)
 
1530
    assert isinstance(to_location, basestring)
 
1531
    
 
1532
    br_to = Branch(to_location, init=True)
 
1533
    br_to.set_root_id(branch_from.get_root_id())
 
1534
    if revision is None:
 
1535
        revno = branch_from.revno()
 
1536
    else:
 
1537
        revno, rev_id = branch_from.get_revision_info(revision)
 
1538
    br_to.update_revisions(branch_from, stop_revision=revno)
 
1539
    merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
1540
          check_clean=False, ignore_zero=True)
 
1541
    
 
1542
    from_location = pull_loc(branch_from)
 
1543
    br_to.set_parent(pull_loc(branch_from))
 
1544