/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: Martin Pool
  • Date: 2005-09-13 23:42:32 UTC
  • mto: (1185.8.2) (974.1.91)
  • mto: This revision was merged to the branch mainline in revision 1390.
  • Revision ID: mbp@sourcefrog.net-20050913234232-4d901f2d843a35f3
- ignore .DS_Store by default

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
 
 
813
        try:
 
814
            revision_ids = self.missing_revisions(other, stop_revision)
 
815
        except DivergedBranches, e:
 
816
            try:
 
817
                if stop_revision is None:
 
818
                    end_revision = other.last_patch()
 
819
                revision_ids = get_intervening_revisions(self.last_patch(), 
 
820
                                                         end_revision, other)
 
821
                assert self.last_patch() not in revision_ids
 
822
            except bzrlib.errors.NotAncestor:
 
823
                raise e
 
824
 
 
825
        if len(revision_ids) > 0:
 
826
            count = greedy_fetch(self, other, revision_ids[-1], pb)[0]
 
827
        else:
 
828
            count = 0
 
829
        self.append_revision(*revision_ids)
 
830
        ## note("Added %d revisions." % count)
 
831
        pb.clear()
 
832
 
 
833
    def install_revisions(self, other, revision_ids, pb):
832
834
        if hasattr(other.revision_store, "prefetch"):
833
835
            other.revision_store.prefetch(revision_ids)
834
836
        if hasattr(other.inventory_store, "prefetch"):
835
 
            inventory_ids = [other.get_revision(r).inventory_id
836
 
                             for r in revision_ids]
 
837
            inventory_ids = []
 
838
            for rev_id in revision_ids:
 
839
                try:
 
840
                    revision = other.get_revision(rev_id).inventory_id
 
841
                    inventory_ids.append(revision)
 
842
                except bzrlib.errors.NoSuchRevision:
 
843
                    pass
837
844
            other.inventory_store.prefetch(inventory_ids)
 
845
 
 
846
        if pb is None:
 
847
            pb = bzrlib.ui.ui_factory.progress_bar()
838
848
                
839
849
        revisions = []
840
850
        needed_texts = set()
841
851
        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)
 
852
 
 
853
        failures = set()
 
854
        for i, rev_id in enumerate(revision_ids):
 
855
            pb.update('fetching revision', i+1, len(revision_ids))
 
856
            try:
 
857
                rev = other.get_revision(rev_id)
 
858
            except bzrlib.errors.NoSuchRevision:
 
859
                failures.add(rev_id)
 
860
                continue
 
861
 
846
862
            revisions.append(rev)
847
863
            inv = other.get_inventory(str(rev.inventory_id))
848
864
            for key, entry in inv.iter_entries():
853
869
 
854
870
        pb.clear()
855
871
                    
856
 
        count = self.text_store.copy_multi(other.text_store, needed_texts)
857
 
        print "Added %d texts." % count 
 
872
        count, cp_fail = self.text_store.copy_multi(other.text_store, 
 
873
                                                    needed_texts)
 
874
        #print "Added %d texts." % count 
858
875
        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 
 
876
        count, cp_fail = self.inventory_store.copy_multi(other.inventory_store, 
 
877
                                                         inventory_ids)
 
878
        #print "Added %d inventories." % count 
862
879
        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
 
        
 
880
 
 
881
        count, cp_fail = self.revision_store.copy_multi(other.revision_store, 
 
882
                                                          revision_ids,
 
883
                                                          permit_failure=True)
 
884
        assert len(cp_fail) == 0 
 
885
        return count, failures
 
886
       
 
887
 
870
888
    def commit(self, *args, **kw):
871
889
        from bzrlib.commit import commit
872
890
        commit(self, *args, **kw)
874
892
 
875
893
    def lookup_revision(self, revision):
876
894
        """Return the revision identifier for a given revision information."""
877
 
        revno, info = self.get_revision_info(revision)
 
895
        revno, info = self._get_revision_info(revision)
878
896
        return info
879
897
 
 
898
 
 
899
    def revision_id_to_revno(self, revision_id):
 
900
        """Given a revision id, return its revno"""
 
901
        history = self.revision_history()
 
902
        try:
 
903
            return history.index(revision_id) + 1
 
904
        except ValueError:
 
905
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
906
 
 
907
 
880
908
    def get_revision_info(self, revision):
881
909
        """Return (revno, revision id) for revision identifier.
882
910
 
885
913
        revision can also be a string, in which case it is parsed for something like
886
914
            'date:' or 'revid:' etc.
887
915
        """
 
916
        revno, rev_id = self._get_revision_info(revision)
 
917
        if revno is None:
 
918
            raise bzrlib.errors.NoSuchRevision(self, revision)
 
919
        return revno, rev_id
 
920
 
 
921
    def get_rev_id(self, revno, history=None):
 
922
        """Find the revision id of the specified revno."""
 
923
        if revno == 0:
 
924
            return None
 
925
        if history is None:
 
926
            history = self.revision_history()
 
927
        elif revno <= 0 or revno > len(history):
 
928
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
929
        return history[revno - 1]
 
930
 
 
931
    def _get_revision_info(self, revision):
 
932
        """Return (revno, revision id) for revision specifier.
 
933
 
 
934
        revision can be an integer, in which case it is assumed to be revno
 
935
        (though this will translate negative values into positive ones)
 
936
        revision can also be a string, in which case it is parsed for something
 
937
        like 'date:' or 'revid:' etc.
 
938
 
 
939
        A revid is always returned.  If it is None, the specifier referred to
 
940
        the null revision.  If the revid does not occur in the revision
 
941
        history, revno will be None.
 
942
        """
 
943
        
888
944
        if revision is None:
889
945
            return 0, None
890
946
        revno = None
894
950
            pass
895
951
        revs = self.revision_history()
896
952
        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
953
            if revision < 0:
901
954
                revno = len(revs) + revision + 1
902
955
            else:
903
956
                revno = revision
 
957
            rev_id = self.get_rev_id(revno, revs)
904
958
        elif isinstance(revision, basestring):
905
959
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
906
960
                if revision.startswith(prefix):
907
 
                    revno = func(self, revs, revision)
 
961
                    result = func(self, revs, revision)
 
962
                    if len(result) > 1:
 
963
                        revno, rev_id = result
 
964
                    else:
 
965
                        revno = result[0]
 
966
                        rev_id = self.get_rev_id(revno, revs)
908
967
                    break
909
968
            else:
910
 
                raise BzrError('No namespace registered for string: %r' % revision)
 
969
                raise BzrError('No namespace registered for string: %r' %
 
970
                               revision)
 
971
        else:
 
972
            raise TypeError('Unhandled revision type %s' % revision)
911
973
 
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]
 
974
        if revno is None:
 
975
            if rev_id is None:
 
976
                raise bzrlib.errors.NoSuchRevision(self, revision)
 
977
        return revno, rev_id
915
978
 
916
979
    def _namespace_revno(self, revs, revision):
917
980
        """Lookup a revision by revision number"""
918
981
        assert revision.startswith('revno:')
919
982
        try:
920
 
            return int(revision[6:])
 
983
            return (int(revision[6:]),)
921
984
        except ValueError:
922
985
            return None
923
986
    REVISION_NAMESPACES['revno:'] = _namespace_revno
924
987
 
925
988
    def _namespace_revid(self, revs, revision):
926
989
        assert revision.startswith('revid:')
 
990
        rev_id = revision[len('revid:'):]
927
991
        try:
928
 
            return revs.index(revision[6:]) + 1
 
992
            return revs.index(rev_id) + 1, rev_id
929
993
        except ValueError:
930
 
            return None
 
994
            return None, rev_id
931
995
    REVISION_NAMESPACES['revid:'] = _namespace_revid
932
996
 
933
997
    def _namespace_last(self, revs, revision):
935
999
        try:
936
1000
            offset = int(revision[5:])
937
1001
        except ValueError:
938
 
            return None
 
1002
            return (None,)
939
1003
        else:
940
1004
            if offset <= 0:
941
1005
                raise BzrError('You must supply a positive value for --revision last:XXX')
942
 
            return len(revs) - offset + 1
 
1006
            return (len(revs) - offset + 1,)
943
1007
    REVISION_NAMESPACES['last:'] = _namespace_last
944
1008
 
945
1009
    def _namespace_tag(self, revs, revision):
1020
1084
                # TODO: Handle timezone.
1021
1085
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1022
1086
                if first >= dt and (last is None or dt >= last):
1023
 
                    return i+1
 
1087
                    return (i+1,)
1024
1088
        else:
1025
1089
            for i in range(len(revs)):
1026
1090
                r = self.get_revision(revs[i])
1027
1091
                # TODO: Handle timezone.
1028
1092
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1029
1093
                if first <= dt and (last is None or dt <= last):
1030
 
                    return i+1
 
1094
                    return (i+1,)
1031
1095
    REVISION_NAMESPACES['date:'] = _namespace_date
1032
1096
 
1033
1097
    def revision_tree(self, revision_id):
1098
1162
 
1099
1163
            inv.rename(file_id, to_dir_id, to_tail)
1100
1164
 
1101
 
            print "%s => %s" % (from_rel, to_rel)
1102
 
 
1103
1165
            from_abs = self.abspath(from_rel)
1104
1166
            to_abs = self.abspath(to_rel)
1105
1167
            try:
1124
1186
 
1125
1187
        Note that to_name is only the last component of the new name;
1126
1188
        this doesn't change the directory.
 
1189
 
 
1190
        This returns a list of (from_path, to_path) pairs for each
 
1191
        entry that is moved.
1127
1192
        """
 
1193
        result = []
1128
1194
        self.lock_write()
1129
1195
        try:
1130
1196
            ## TODO: Option to move IDs only
1165
1231
            for f in from_paths:
1166
1232
                name_tail = splitpath(f)[-1]
1167
1233
                dest_path = appendpath(to_name, name_tail)
1168
 
                print "%s => %s" % (f, dest_path)
 
1234
                result.append((f, dest_path))
1169
1235
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1170
1236
                try:
1171
1237
                    os.rename(self.abspath(f), self.abspath(dest_path))
1177
1243
        finally:
1178
1244
            self.unlock()
1179
1245
 
 
1246
        return result
 
1247
 
1180
1248
 
1181
1249
    def revert(self, filenames, old_tree=None, backups=True):
1182
1250
        """Restore selected files to the versions from a previous tree.
1264
1332
            self.unlock()
1265
1333
 
1266
1334
 
 
1335
    def get_parent(self):
 
1336
        """Return the parent location of the branch.
 
1337
 
 
1338
        This is the default location for push/pull/missing.  The usual
 
1339
        pattern is that the user can override it by specifying a
 
1340
        location.
 
1341
        """
 
1342
        import errno
 
1343
        _locs = ['parent', 'pull', 'x-pull']
 
1344
        for l in _locs:
 
1345
            try:
 
1346
                return self.controlfile(l, 'r').read().strip('\n')
 
1347
            except IOError, e:
 
1348
                if e.errno != errno.ENOENT:
 
1349
                    raise
 
1350
        return None
 
1351
 
 
1352
 
 
1353
    def set_parent(self, url):
 
1354
        # TODO: Maybe delete old location files?
 
1355
        from bzrlib.atomicfile import AtomicFile
 
1356
        self.lock_write()
 
1357
        try:
 
1358
            f = AtomicFile(self.controlfilename('parent'))
 
1359
            try:
 
1360
                f.write(url + '\n')
 
1361
                f.commit()
 
1362
            finally:
 
1363
                f.close()
 
1364
        finally:
 
1365
            self.unlock()
 
1366
 
 
1367
    def check_revno(self, revno):
 
1368
        """\
 
1369
        Check whether a revno corresponds to any revision.
 
1370
        Zero (the NULL revision) is considered valid.
 
1371
        """
 
1372
        if revno != 0:
 
1373
            self.check_real_revno(revno)
 
1374
            
 
1375
    def check_real_revno(self, revno):
 
1376
        """\
 
1377
        Check whether a revno corresponds to a real revision.
 
1378
        Zero (the NULL revision) is considered invalid
 
1379
        """
 
1380
        if revno < 1 or revno > self.revno():
 
1381
            raise InvalidRevisionNumber(revno)
 
1382
        
 
1383
        
 
1384
 
1267
1385
 
1268
1386
class ScratchBranch(Branch):
1269
1387
    """Special test class: a branch that cleans up after itself.
1311
1429
        os.rmdir(base)
1312
1430
        copytree(self.base, base, symlinks=True)
1313
1431
        return ScratchBranch(base=base)
 
1432
 
 
1433
 
1314
1434
        
1315
1435
    def __del__(self):
1316
1436
        self.destroy()
1386
1506
    """Return a new tree-root file id."""
1387
1507
    return gen_file_id('TREE_ROOT')
1388
1508
 
 
1509
 
 
1510
def pull_loc(branch):
 
1511
    # TODO: Should perhaps just make attribute be 'base' in
 
1512
    # RemoteBranch and Branch?
 
1513
    if hasattr(branch, "baseurl"):
 
1514
        return branch.baseurl
 
1515
    else:
 
1516
        return branch.base
 
1517
 
 
1518
 
 
1519
def copy_branch(branch_from, to_location, revision=None):
 
1520
    """Copy branch_from into the existing directory to_location.
 
1521
 
 
1522
    revision
 
1523
        If not None, only revisions up to this point will be copied.
 
1524
        The head of the new branch will be that revision.
 
1525
 
 
1526
    to_location
 
1527
        The name of a local directory that exists but is empty.
 
1528
    """
 
1529
    from bzrlib.merge import merge
 
1530
    from bzrlib.branch import Branch
 
1531
 
 
1532
    assert isinstance(branch_from, Branch)
 
1533
    assert isinstance(to_location, basestring)
 
1534
    
 
1535
    br_to = Branch(to_location, init=True)
 
1536
    br_to.set_root_id(branch_from.get_root_id())
 
1537
    if revision is None:
 
1538
        revno = branch_from.revno()
 
1539
    else:
 
1540
        revno, rev_id = branch_from.get_revision_info(revision)
 
1541
    br_to.update_revisions(branch_from, stop_revision=revno)
 
1542
    merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
1543
          check_clean=False, ignore_zero=True)
 
1544
    
 
1545
    from_location = pull_loc(branch_from)
 
1546
    br_to.set_parent(pull_loc(branch_from))
 
1547