/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

- merge various windows and other fixes from Ollie Rutherfurd
  
1179: changed diff help example to -r1..2 from deprecated -r1:2
1178: fixed \r\n -> \n conversion in branch._check_format
1177: disable urlgrabber on win32, since it converts / -> \
1176: changed assert path.startswith('./') -> '.'+os.sep in merge.py
1175: replaced os.spawnvp with subprocess.call in msgeditor.py
1174: os.name == 'windows' -> 'nt', check for %EDITOR% on win32
1173: fixed bzr mv filename newfilename, re-enabled test_mv_modes

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)
594
585
            try:
595
586
                return self.revision_store[revision_id]
596
587
            except IndexError:
597
 
                raise bzrlib.errors.NoSuchRevision(revision_id)
 
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
 
 
809
        pb = bzrlib.ui.ui_factory.progress_bar()
829
810
        pb.update('comparing histories')
 
811
 
830
812
        revision_ids = self.missing_revisions(other, stop_revision)
831
813
 
 
814
        if len(revision_ids) > 0:
 
815
            count = greedy_fetch(self, other, revision_ids[-1], pb)[0]
 
816
        else:
 
817
            count = 0
 
818
        self.append_revision(*revision_ids)
 
819
        ## note("Added %d revisions." % count)
 
820
        pb.clear()
 
821
 
 
822
    def install_revisions(self, other, revision_ids, pb):
832
823
        if hasattr(other.revision_store, "prefetch"):
833
824
            other.revision_store.prefetch(revision_ids)
834
825
        if hasattr(other.inventory_store, "prefetch"):
835
826
            inventory_ids = [other.get_revision(r).inventory_id
836
827
                             for r in revision_ids]
837
828
            other.inventory_store.prefetch(inventory_ids)
 
829
 
 
830
        if pb is None:
 
831
            pb = bzrlib.ui.ui_factory.progress_bar()
838
832
                
839
833
        revisions = []
840
834
        needed_texts = set()
841
835
        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)
 
836
 
 
837
        failures = set()
 
838
        for i, rev_id in enumerate(revision_ids):
 
839
            pb.update('fetching revision', i+1, len(revision_ids))
 
840
            try:
 
841
                rev = other.get_revision(rev_id)
 
842
            except bzrlib.errors.NoSuchRevision:
 
843
                failures.add(rev_id)
 
844
                continue
 
845
 
846
846
            revisions.append(rev)
847
847
            inv = other.get_inventory(str(rev.inventory_id))
848
848
            for key, entry in inv.iter_entries():
853
853
 
854
854
        pb.clear()
855
855
                    
856
 
        count = self.text_store.copy_multi(other.text_store, needed_texts)
857
 
        print "Added %d texts." % count 
 
856
        count, cp_fail = self.text_store.copy_multi(other.text_store, 
 
857
                                                    needed_texts)
 
858
        #print "Added %d texts." % count 
858
859
        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 
 
860
        count, cp_fail = self.inventory_store.copy_multi(other.inventory_store, 
 
861
                                                         inventory_ids)
 
862
        #print "Added %d inventories." % count 
862
863
        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
 
        
 
864
 
 
865
        count, cp_fail = self.revision_store.copy_multi(other.revision_store, 
 
866
                                                          revision_ids,
 
867
                                                          permit_failure=True)
 
868
        assert len(cp_fail) == 0 
 
869
        return count, failures
 
870
       
 
871
 
870
872
    def commit(self, *args, **kw):
871
873
        from bzrlib.commit import commit
872
874
        commit(self, *args, **kw)
874
876
 
875
877
    def lookup_revision(self, revision):
876
878
        """Return the revision identifier for a given revision information."""
877
 
        revno, info = self.get_revision_info(revision)
 
879
        revno, info = self._get_revision_info(revision)
878
880
        return info
879
881
 
 
882
 
 
883
    def revision_id_to_revno(self, revision_id):
 
884
        """Given a revision id, return its revno"""
 
885
        history = self.revision_history()
 
886
        try:
 
887
            return history.index(revision_id) + 1
 
888
        except ValueError:
 
889
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
890
 
 
891
 
880
892
    def get_revision_info(self, revision):
881
893
        """Return (revno, revision id) for revision identifier.
882
894
 
885
897
        revision can also be a string, in which case it is parsed for something like
886
898
            'date:' or 'revid:' etc.
887
899
        """
 
900
        revno, rev_id = self._get_revision_info(revision)
 
901
        if revno is None:
 
902
            raise bzrlib.errors.NoSuchRevision(self, revision)
 
903
        return revno, rev_id
 
904
 
 
905
    def get_rev_id(self, revno, history=None):
 
906
        """Find the revision id of the specified revno."""
 
907
        if revno == 0:
 
908
            return None
 
909
        if history is None:
 
910
            history = self.revision_history()
 
911
        elif revno <= 0 or revno > len(history):
 
912
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
913
        return history[revno - 1]
 
914
 
 
915
    def _get_revision_info(self, revision):
 
916
        """Return (revno, revision id) for revision specifier.
 
917
 
 
918
        revision can be an integer, in which case it is assumed to be revno
 
919
        (though this will translate negative values into positive ones)
 
920
        revision can also be a string, in which case it is parsed for something
 
921
        like 'date:' or 'revid:' etc.
 
922
 
 
923
        A revid is always returned.  If it is None, the specifier referred to
 
924
        the null revision.  If the revid does not occur in the revision
 
925
        history, revno will be None.
 
926
        """
 
927
        
888
928
        if revision is None:
889
929
            return 0, None
890
930
        revno = None
894
934
            pass
895
935
        revs = self.revision_history()
896
936
        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
937
            if revision < 0:
901
938
                revno = len(revs) + revision + 1
902
939
            else:
903
940
                revno = revision
 
941
            rev_id = self.get_rev_id(revno, revs)
904
942
        elif isinstance(revision, basestring):
905
943
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
906
944
                if revision.startswith(prefix):
907
 
                    revno = func(self, revs, revision)
 
945
                    result = func(self, revs, revision)
 
946
                    if len(result) > 1:
 
947
                        revno, rev_id = result
 
948
                    else:
 
949
                        revno = result[0]
 
950
                        rev_id = self.get_rev_id(revno, revs)
908
951
                    break
909
952
            else:
910
 
                raise BzrError('No namespace registered for string: %r' % revision)
 
953
                raise BzrError('No namespace registered for string: %r' %
 
954
                               revision)
 
955
        else:
 
956
            raise TypeError('Unhandled revision type %s' % revision)
911
957
 
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]
 
958
        if revno is None:
 
959
            if rev_id is None:
 
960
                raise bzrlib.errors.NoSuchRevision(self, revision)
 
961
        return revno, rev_id
915
962
 
916
963
    def _namespace_revno(self, revs, revision):
917
964
        """Lookup a revision by revision number"""
918
965
        assert revision.startswith('revno:')
919
966
        try:
920
 
            return int(revision[6:])
 
967
            return (int(revision[6:]),)
921
968
        except ValueError:
922
969
            return None
923
970
    REVISION_NAMESPACES['revno:'] = _namespace_revno
924
971
 
925
972
    def _namespace_revid(self, revs, revision):
926
973
        assert revision.startswith('revid:')
 
974
        rev_id = revision[len('revid:'):]
927
975
        try:
928
 
            return revs.index(revision[6:]) + 1
 
976
            return revs.index(rev_id) + 1, rev_id
929
977
        except ValueError:
930
 
            return None
 
978
            return None, rev_id
931
979
    REVISION_NAMESPACES['revid:'] = _namespace_revid
932
980
 
933
981
    def _namespace_last(self, revs, revision):
935
983
        try:
936
984
            offset = int(revision[5:])
937
985
        except ValueError:
938
 
            return None
 
986
            return (None,)
939
987
        else:
940
988
            if offset <= 0:
941
989
                raise BzrError('You must supply a positive value for --revision last:XXX')
942
 
            return len(revs) - offset + 1
 
990
            return (len(revs) - offset + 1,)
943
991
    REVISION_NAMESPACES['last:'] = _namespace_last
944
992
 
945
993
    def _namespace_tag(self, revs, revision):
1020
1068
                # TODO: Handle timezone.
1021
1069
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1022
1070
                if first >= dt and (last is None or dt >= last):
1023
 
                    return i+1
 
1071
                    return (i+1,)
1024
1072
        else:
1025
1073
            for i in range(len(revs)):
1026
1074
                r = self.get_revision(revs[i])
1027
1075
                # TODO: Handle timezone.
1028
1076
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1029
1077
                if first <= dt and (last is None or dt <= last):
1030
 
                    return i+1
 
1078
                    return (i+1,)
1031
1079
    REVISION_NAMESPACES['date:'] = _namespace_date
1032
1080
 
1033
1081
    def revision_tree(self, revision_id):
1098
1146
 
1099
1147
            inv.rename(file_id, to_dir_id, to_tail)
1100
1148
 
1101
 
            print "%s => %s" % (from_rel, to_rel)
1102
 
 
1103
1149
            from_abs = self.abspath(from_rel)
1104
1150
            to_abs = self.abspath(to_rel)
1105
1151
            try:
1124
1170
 
1125
1171
        Note that to_name is only the last component of the new name;
1126
1172
        this doesn't change the directory.
 
1173
 
 
1174
        This returns a list of (from_path, to_path) pairs for each
 
1175
        entry that is moved.
1127
1176
        """
 
1177
        result = []
1128
1178
        self.lock_write()
1129
1179
        try:
1130
1180
            ## TODO: Option to move IDs only
1165
1215
            for f in from_paths:
1166
1216
                name_tail = splitpath(f)[-1]
1167
1217
                dest_path = appendpath(to_name, name_tail)
1168
 
                print "%s => %s" % (f, dest_path)
 
1218
                result.append((f, dest_path))
1169
1219
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1170
1220
                try:
1171
1221
                    os.rename(self.abspath(f), self.abspath(dest_path))
1177
1227
        finally:
1178
1228
            self.unlock()
1179
1229
 
 
1230
        return result
 
1231
 
1180
1232
 
1181
1233
    def revert(self, filenames, old_tree=None, backups=True):
1182
1234
        """Restore selected files to the versions from a previous tree.
1264
1316
            self.unlock()
1265
1317
 
1266
1318
 
 
1319
    def get_parent(self):
 
1320
        """Return the parent location of the branch.
 
1321
 
 
1322
        This is the default location for push/pull/missing.  The usual
 
1323
        pattern is that the user can override it by specifying a
 
1324
        location.
 
1325
        """
 
1326
        import errno
 
1327
        _locs = ['parent', 'pull', 'x-pull']
 
1328
        for l in _locs:
 
1329
            try:
 
1330
                return self.controlfile(l, 'r').read().strip('\n')
 
1331
            except IOError, e:
 
1332
                if e.errno != errno.ENOENT:
 
1333
                    raise
 
1334
        return None
 
1335
 
 
1336
 
 
1337
    def set_parent(self, url):
 
1338
        # TODO: Maybe delete old location files?
 
1339
        from bzrlib.atomicfile import AtomicFile
 
1340
        self.lock_write()
 
1341
        try:
 
1342
            f = AtomicFile(self.controlfilename('parent'))
 
1343
            try:
 
1344
                f.write(url + '\n')
 
1345
                f.commit()
 
1346
            finally:
 
1347
                f.close()
 
1348
        finally:
 
1349
            self.unlock()
 
1350
 
 
1351
    def check_revno(self, revno):
 
1352
        """\
 
1353
        Check whether a revno corresponds to any revision.
 
1354
        Zero (the NULL revision) is considered valid.
 
1355
        """
 
1356
        if revno != 0:
 
1357
            self.check_real_revno(revno)
 
1358
            
 
1359
    def check_real_revno(self, revno):
 
1360
        """\
 
1361
        Check whether a revno corresponds to a real revision.
 
1362
        Zero (the NULL revision) is considered invalid
 
1363
        """
 
1364
        if revno < 1 or revno > self.revno():
 
1365
            raise InvalidRevisionNumber(revno)
 
1366
        
 
1367
        
 
1368
 
1267
1369
 
1268
1370
class ScratchBranch(Branch):
1269
1371
    """Special test class: a branch that cleans up after itself.
1311
1413
        os.rmdir(base)
1312
1414
        copytree(self.base, base, symlinks=True)
1313
1415
        return ScratchBranch(base=base)
 
1416
 
 
1417
 
1314
1418
        
1315
1419
    def __del__(self):
1316
1420
        self.destroy()
1386
1490
    """Return a new tree-root file id."""
1387
1491
    return gen_file_id('TREE_ROOT')
1388
1492
 
 
1493
 
 
1494
def pull_loc(branch):
 
1495
    # TODO: Should perhaps just make attribute be 'base' in
 
1496
    # RemoteBranch and Branch?
 
1497
    if hasattr(branch, "baseurl"):
 
1498
        return branch.baseurl
 
1499
    else:
 
1500
        return branch.base
 
1501
 
 
1502
 
 
1503
def copy_branch(branch_from, to_location, revision=None):
 
1504
    """Copy branch_from into the existing directory to_location.
 
1505
 
 
1506
    revision
 
1507
        If not None, only revisions up to this point will be copied.
 
1508
        The head of the new branch will be that revision.
 
1509
 
 
1510
    to_location
 
1511
        The name of a local directory that exists but is empty.
 
1512
    """
 
1513
    from bzrlib.merge import merge
 
1514
    from bzrlib.branch import Branch
 
1515
 
 
1516
    assert isinstance(branch_from, Branch)
 
1517
    assert isinstance(to_location, basestring)
 
1518
    
 
1519
    br_to = Branch(to_location, init=True)
 
1520
    br_to.set_root_id(branch_from.get_root_id())
 
1521
    if revision is None:
 
1522
        revno = branch_from.revno()
 
1523
    else:
 
1524
        revno, rev_id = branch_from.get_revision_info(revision)
 
1525
    br_to.update_revisions(branch_from, stop_revision=revno)
 
1526
    merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
1527
          check_clean=False, ignore_zero=True)
 
1528
    
 
1529
    from_location = pull_loc(branch_from)
 
1530
    br_to.set_parent(pull_loc(branch_from))
 
1531