~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Robert Collins
  • Date: 2005-09-26 08:56:15 UTC
  • mto: (1092.3.4)
  • mto: This revision was merged to the branch mainline in revision 1390.
  • Revision ID: robertc@robertcollins.net-20050926085615-99b8fb35f41b541d
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid

Show diffs side-by-side

added added

removed removed

Lines of Context:
21
21
import bzrlib
22
22
from bzrlib.trace import mutter, note
23
23
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
24
 
     splitpath, \
25
 
     sha_file, appendpath, file_kind
 
24
     rename, splitpath, sha_file, appendpath, file_kind
26
25
 
27
 
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId
28
 
import bzrlib.errors
 
26
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId, \
 
27
     DivergedBranches, NotBranchError
29
28
from bzrlib.textui import show_status
30
29
from bzrlib.revision import Revision
31
 
from bzrlib.xml import unpack_xml
32
30
from bzrlib.delta import compare_trees
33
31
from bzrlib.tree import EmptyTree, RevisionTree
 
32
import bzrlib.xml
34
33
import bzrlib.ui
35
34
 
36
35
 
43
42
# repeatedly to calculate deltas.  We could perhaps have a weakref
44
43
# cache in memory to make this faster.
45
44
 
46
 
# TODO: please move the revision-string syntax stuff out of the branch
47
 
# object; it's clutter
48
 
 
49
 
 
50
 
def find_branch(f, **args):
51
 
    if f and (f.startswith('http://') or f.startswith('https://')):
52
 
        import remotebranch 
53
 
        return remotebranch.RemoteBranch(f, **args)
54
 
    else:
55
 
        return Branch(f, **args)
56
 
 
57
 
 
58
 
def find_cached_branch(f, cache_root, **args):
59
 
    from remotebranch import RemoteBranch
60
 
    br = find_branch(f, **args)
61
 
    def cacheify(br, store_name):
62
 
        from meta_store import CachedStore
63
 
        cache_path = os.path.join(cache_root, store_name)
64
 
        os.mkdir(cache_path)
65
 
        new_store = CachedStore(getattr(br, store_name), cache_path)
66
 
        setattr(br, store_name, new_store)
67
 
 
68
 
    if isinstance(br, RemoteBranch):
69
 
        cacheify(br, 'inventory_store')
70
 
        cacheify(br, 'text_store')
71
 
        cacheify(br, 'revision_store')
72
 
    return br
73
 
 
 
45
def find_branch(*ignored, **ignored_too):
 
46
    # XXX: leave this here for about one release, then remove it
 
47
    raise NotImplementedError('find_branch() is not supported anymore, '
 
48
                              'please use one of the new branch constructors')
74
49
 
75
50
def _relpath(base, path):
76
51
    """Return path relative to base, or raise exception.
94
69
        if tail:
95
70
            s.insert(0, tail)
96
71
    else:
97
 
        from errors import NotBranchError
98
72
        raise NotBranchError("path %r is not within branch %r" % (rp, base))
99
73
 
100
74
    return os.sep.join(s)
128
102
        head, tail = os.path.split(f)
129
103
        if head == f:
130
104
            # reached the root, whatever that may be
131
 
            raise bzrlib.errors.NotBranchError('%s is not in a branch' % orig_f)
 
105
            raise NotBranchError('%s is not in a branch' % orig_f)
132
106
        f = head
133
107
 
134
108
 
135
109
 
136
 
# XXX: move into bzrlib.errors; subclass BzrError    
137
 
class DivergedBranches(Exception):
138
 
    def __init__(self, branch1, branch2):
139
 
        self.branch1 = branch1
140
 
        self.branch2 = branch2
141
 
        Exception.__init__(self, "These branches have diverged.")
142
 
 
143
110
 
144
111
######################################################################
145
112
# branch objects
148
115
    """Branch holding a history of revisions.
149
116
 
150
117
    base
151
 
        Base directory of the branch.
 
118
        Base directory/url of the branch.
 
119
    """
 
120
    base = None
 
121
 
 
122
    def __init__(self, *ignored, **ignored_too):
 
123
        raise NotImplementedError('The Branch class is abstract')
 
124
 
 
125
    @staticmethod
 
126
    def open(base):
 
127
        """Open an existing branch, rooted at 'base' (url)"""
 
128
        if base and (base.startswith('http://') or base.startswith('https://')):
 
129
            from bzrlib.remotebranch import RemoteBranch
 
130
            return RemoteBranch(base, find_root=False)
 
131
        else:
 
132
            return LocalBranch(base, find_root=False)
 
133
 
 
134
    @staticmethod
 
135
    def open_containing(url):
 
136
        """Open an existing branch which contains url.
 
137
        
 
138
        This probes for a branch at url, and searches upwards from there.
 
139
        """
 
140
        if url and (url.startswith('http://') or url.startswith('https://')):
 
141
            from bzrlib.remotebranch import RemoteBranch
 
142
            return RemoteBranch(url)
 
143
        else:
 
144
            return LocalBranch(url)
 
145
 
 
146
    @staticmethod
 
147
    def initialize(base):
 
148
        """Create a new branch, rooted at 'base' (url)"""
 
149
        if base and (base.startswith('http://') or base.startswith('https://')):
 
150
            from bzrlib.remotebranch import RemoteBranch
 
151
            return RemoteBranch(base, init=True)
 
152
        else:
 
153
            return LocalBranch(base, init=True)
 
154
 
 
155
    def setup_caching(self, cache_root):
 
156
        """Subclasses that care about caching should override this, and set
 
157
        up cached stores located under cache_root.
 
158
        """
 
159
 
 
160
 
 
161
class LocalBranch(Branch):
 
162
    """A branch stored in the actual filesystem.
 
163
 
 
164
    Note that it's "local" in the context of the filesystem; it doesn't
 
165
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
 
166
    it's writable, and can be accessed via the normal filesystem API.
152
167
 
153
168
    _lock_mode
154
169
        None, or 'r' or 'w'
160
175
    _lock
161
176
        Lock object from bzrlib.lock.
162
177
    """
163
 
    base = None
 
178
    # We actually expect this class to be somewhat short-lived; part of its
 
179
    # purpose is to try to isolate what bits of the branch logic are tied to
 
180
    # filesystem access, so that in a later step, we can extricate them to
 
181
    # a separarte ("storage") class.
164
182
    _lock_mode = None
165
183
    _lock_count = None
166
184
    _lock = None
167
 
    
168
 
    # Map some sort of prefix into a namespace
169
 
    # stuff like "revno:10", "revid:", etc.
170
 
    # This should match a prefix with a function which accepts
171
 
    REVISION_NAMESPACES = {}
172
185
 
173
186
    def __init__(self, base, init=False, find_root=True):
174
187
        """Create new branch object at a particular location.
175
188
 
176
 
        base -- Base directory for the branch.
 
189
        base -- Base directory for the branch. May be a file:// url.
177
190
        
178
191
        init -- If True, create new control files in a previously
179
192
             unversioned directory.  If False, the branch must already
192
205
        elif find_root:
193
206
            self.base = find_branch_root(base)
194
207
        else:
 
208
            if base.startswith("file://"):
 
209
                base = base[7:]
195
210
            self.base = os.path.realpath(base)
196
211
            if not isdir(self.controlfilename('.')):
197
 
                from errors import NotBranchError
198
212
                raise NotBranchError("not a bzr branch: %s" % quotefn(base),
199
213
                                     ['use "bzr init" to initialize a new working tree',
200
214
                                      'current bzr can only operate from top-of-tree'])
214
228
 
215
229
    def __del__(self):
216
230
        if self._lock_mode or self._lock:
217
 
            from warnings import warn
 
231
            from bzrlib.warnings import warn
218
232
            warn("branch %r was not explicitly unlocked" % self)
219
233
            self._lock.unlock()
220
234
 
221
 
 
222
235
    def lock_write(self):
223
236
        if self._lock_mode:
224
237
            if self._lock_mode != 'w':
225
 
                from errors import LockError
 
238
                from bzrlib.errors import LockError
226
239
                raise LockError("can't upgrade to a write lock from %r" %
227
240
                                self._lock_mode)
228
241
            self._lock_count += 1
248
261
                        
249
262
    def unlock(self):
250
263
        if not self._lock_mode:
251
 
            from errors import LockError
 
264
            from bzrlib.errors import LockError
252
265
            raise LockError('branch %r is not locked' % (self))
253
266
 
254
267
        if self._lock_count > 1:
302
315
 
303
316
    def _make_control(self):
304
317
        from bzrlib.inventory import Inventory
305
 
        from bzrlib.xml import pack_xml
306
318
        
307
319
        os.mkdir(self.controlfilename([]))
308
320
        self.controlfile('README', 'w').write(
321
333
        # if we want per-tree root ids then this is the place to set
322
334
        # them; they're not needed for now and so ommitted for
323
335
        # simplicity.
324
 
        pack_xml(Inventory(), self.controlfile('inventory','w'))
 
336
        f = self.controlfile('inventory','w')
 
337
        bzrlib.xml.serializer_v4.write_inventory(Inventory(), f)
 
338
 
325
339
 
326
340
    def _check_format(self):
327
341
        """Check this branch format is supported.
335
349
        # on Windows from Linux and so on.  I think it might be better
336
350
        # to always make all internal files in unix format.
337
351
        fmt = self.controlfile('branch-format', 'r').read()
338
 
        fmt.replace('\r\n', '')
 
352
        fmt = fmt.replace('\r\n', '\n')
339
353
        if fmt != BZR_BRANCH_FORMAT:
340
354
            raise BzrError('sorry, branch format %r not supported' % fmt,
341
355
                           ['use a different bzr version',
361
375
    def read_working_inventory(self):
362
376
        """Read the working inventory."""
363
377
        from bzrlib.inventory import Inventory
364
 
        from bzrlib.xml import unpack_xml
365
 
        from time import time
366
 
        before = time()
367
378
        self.lock_read()
368
379
        try:
369
380
            # ElementTree does its own conversion from UTF-8, so open in
370
381
            # binary.
371
 
            inv = unpack_xml(Inventory,
372
 
                             self.controlfile('inventory', 'rb'))
373
 
            mutter("loaded inventory of %d items in %f"
374
 
                   % (len(inv), time() - before))
375
 
            return inv
 
382
            f = self.controlfile('inventory', 'rb')
 
383
            return bzrlib.xml.serializer_v4.read_inventory(f)
376
384
        finally:
377
385
            self.unlock()
378
386
            
384
392
        will be committed to the next revision.
385
393
        """
386
394
        from bzrlib.atomicfile import AtomicFile
387
 
        from bzrlib.xml import pack_xml
388
395
        
389
396
        self.lock_write()
390
397
        try:
391
398
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
392
399
            try:
393
 
                pack_xml(inv, f)
 
400
                bzrlib.xml.serializer_v4.write_inventory(inv, f)
394
401
                f.commit()
395
402
            finally:
396
403
                f.close()
477
484
        """Print `file` to stdout."""
478
485
        self.lock_read()
479
486
        try:
480
 
            tree = self.revision_tree(self.lookup_revision(revno))
 
487
            tree = self.revision_tree(self.get_rev_id(revno))
481
488
            # use inventory as it was in that revision
482
489
            file_id = tree.inventory.path2id(file)
483
490
            if not file_id:
581
588
            f.close()
582
589
 
583
590
 
584
 
    def get_revision_xml(self, revision_id):
 
591
    def get_revision_xml_file(self, revision_id):
585
592
        """Return XML file object for revision object."""
586
593
        if not revision_id or not isinstance(revision_id, basestring):
587
594
            raise InvalidRevisionId(revision_id)
590
597
        try:
591
598
            try:
592
599
                return self.revision_store[revision_id]
593
 
            except IndexError:
 
600
            except (IndexError, KeyError):
594
601
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
595
602
        finally:
596
603
            self.unlock()
597
604
 
598
605
 
 
606
    #deprecated
 
607
    get_revision_xml = get_revision_xml_file
 
608
 
 
609
 
599
610
    def get_revision(self, revision_id):
600
611
        """Return the Revision object for a named revision"""
601
 
        xml_file = self.get_revision_xml(revision_id)
 
612
        xml_file = self.get_revision_xml_file(revision_id)
602
613
 
603
614
        try:
604
 
            r = unpack_xml(Revision, xml_file)
 
615
            r = bzrlib.xml.serializer_v4.read_revision(xml_file)
605
616
        except SyntaxError, e:
606
617
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
607
618
                                         [revision_id,
652
663
               parameter which can be either an integer revno or a
653
664
               string hash."""
654
665
        from bzrlib.inventory import Inventory
655
 
        from bzrlib.xml import unpack_xml
656
666
 
657
 
        return unpack_xml(Inventory, self.get_inventory_xml(inventory_id))
 
667
        f = self.get_inventory_xml_file(inventory_id)
 
668
        return bzrlib.xml.serializer_v4.read_inventory(f)
658
669
 
659
670
 
660
671
    def get_inventory_xml(self, inventory_id):
661
672
        """Get inventory XML as a file object."""
662
673
        return self.inventory_store[inventory_id]
 
674
 
 
675
    get_inventory_xml_file = get_inventory_xml
663
676
            
664
677
 
665
678
    def get_inventory_sha1(self, inventory_id):
695
708
 
696
709
    def common_ancestor(self, other, self_revno=None, other_revno=None):
697
710
        """
698
 
        >>> import commit
 
711
        >>> from bzrlib.commit import commit
699
712
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
700
713
        >>> sb.common_ancestor(sb) == (None, None)
701
714
        True
702
 
        >>> commit.commit(sb, "Committing first revision", verbose=False)
 
715
        >>> commit(sb, "Committing first revision", verbose=False)
703
716
        >>> sb.common_ancestor(sb)[0]
704
717
        1
705
718
        >>> clone = sb.clone()
706
 
        >>> commit.commit(sb, "Committing second revision", verbose=False)
 
719
        >>> commit(sb, "Committing second revision", verbose=False)
707
720
        >>> sb.common_ancestor(sb)[0]
708
721
        2
709
722
        >>> sb.common_ancestor(clone)[0]
710
723
        1
711
 
        >>> commit.commit(clone, "Committing divergent second revision", 
 
724
        >>> commit(clone, "Committing divergent second revision", 
712
725
        ...               verbose=False)
713
726
        >>> sb.common_ancestor(clone)[0]
714
727
        1
805
818
        """Pull in all new revisions from other branch.
806
819
        """
807
820
        from bzrlib.fetch import greedy_fetch
 
821
        from bzrlib.revision import get_intervening_revisions
808
822
 
809
823
        pb = bzrlib.ui.ui_factory.progress_bar()
810
824
        pb.update('comparing histories')
811
 
 
812
 
        revision_ids = self.missing_revisions(other, stop_revision)
813
 
 
814
 
        if len(revision_ids) > 0:
815
 
            count = greedy_fetch(self, other, revision_ids[-1], pb)[0]
 
825
        if stop_revision is None:
 
826
            other_revision = other.last_patch()
816
827
        else:
817
 
            count = 0
 
828
            other_revision = other.get_rev_id(stop_revision)
 
829
        count = greedy_fetch(self, other, other_revision, pb)[0]
 
830
        try:
 
831
            revision_ids = self.missing_revisions(other, stop_revision)
 
832
        except DivergedBranches, e:
 
833
            try:
 
834
                revision_ids = get_intervening_revisions(self.last_patch(), 
 
835
                                                         other_revision, self)
 
836
                assert self.last_patch() not in revision_ids
 
837
            except bzrlib.errors.NotAncestor:
 
838
                raise e
 
839
 
818
840
        self.append_revision(*revision_ids)
819
 
        ## note("Added %d revisions." % count)
820
841
        pb.clear()
821
842
 
822
843
    def install_revisions(self, other, revision_ids, pb):
823
844
        if hasattr(other.revision_store, "prefetch"):
824
845
            other.revision_store.prefetch(revision_ids)
825
846
        if hasattr(other.inventory_store, "prefetch"):
826
 
            inventory_ids = [other.get_revision(r).inventory_id
827
 
                             for r in revision_ids]
 
847
            inventory_ids = []
 
848
            for rev_id in revision_ids:
 
849
                try:
 
850
                    revision = other.get_revision(rev_id).inventory_id
 
851
                    inventory_ids.append(revision)
 
852
                except bzrlib.errors.NoSuchRevision:
 
853
                    pass
828
854
            other.inventory_store.prefetch(inventory_ids)
829
855
 
830
856
        if pb is None:
873
899
        from bzrlib.commit import commit
874
900
        commit(self, *args, **kw)
875
901
        
876
 
 
877
 
    def lookup_revision(self, revision):
878
 
        """Return the revision identifier for a given revision information."""
879
 
        revno, info = self.get_revision_info(revision)
880
 
        return info
881
 
 
882
 
 
883
902
    def revision_id_to_revno(self, revision_id):
884
903
        """Given a revision id, return its revno"""
885
904
        history = self.revision_history()
888
907
        except ValueError:
889
908
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
890
909
 
891
 
 
892
 
    def get_revision_info(self, revision):
893
 
        """Return (revno, revision id) for revision identifier.
894
 
 
895
 
        revision can be an integer, in which case it is assumed to be revno (though
896
 
            this will translate negative values into positive ones)
897
 
        revision can also be a string, in which case it is parsed for something like
898
 
            'date:' or 'revid:' etc.
899
 
        """
900
 
        if revision is None:
901
 
            return 0, None
902
 
        revno = None
903
 
        try:# Convert to int if possible
904
 
            revision = int(revision)
905
 
        except ValueError:
906
 
            pass
907
 
        revs = self.revision_history()
908
 
        if isinstance(revision, int):
909
 
            if revision == 0:
910
 
                return 0, None
911
 
            # Mabye we should do this first, but we don't need it if revision == 0
912
 
            if revision < 0:
913
 
                revno = len(revs) + revision + 1
914
 
            else:
915
 
                revno = revision
916
 
        elif isinstance(revision, basestring):
917
 
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
918
 
                if revision.startswith(prefix):
919
 
                    revno = func(self, revs, revision)
920
 
                    break
921
 
            else:
922
 
                raise BzrError('No namespace registered for string: %r' % revision)
923
 
 
924
 
        if revno is None or revno <= 0 or revno > len(revs):
925
 
            raise BzrError("no such revision %s" % revision)
926
 
        return revno, revs[revno-1]
927
 
 
928
 
    def _namespace_revno(self, revs, revision):
929
 
        """Lookup a revision by revision number"""
930
 
        assert revision.startswith('revno:')
931
 
        try:
932
 
            return int(revision[6:])
933
 
        except ValueError:
934
 
            return None
935
 
    REVISION_NAMESPACES['revno:'] = _namespace_revno
936
 
 
937
 
    def _namespace_revid(self, revs, revision):
938
 
        assert revision.startswith('revid:')
939
 
        try:
940
 
            return revs.index(revision[6:]) + 1
941
 
        except ValueError:
942
 
            return None
943
 
    REVISION_NAMESPACES['revid:'] = _namespace_revid
944
 
 
945
 
    def _namespace_last(self, revs, revision):
946
 
        assert revision.startswith('last:')
947
 
        try:
948
 
            offset = int(revision[5:])
949
 
        except ValueError:
950
 
            return None
951
 
        else:
952
 
            if offset <= 0:
953
 
                raise BzrError('You must supply a positive value for --revision last:XXX')
954
 
            return len(revs) - offset + 1
955
 
    REVISION_NAMESPACES['last:'] = _namespace_last
956
 
 
957
 
    def _namespace_tag(self, revs, revision):
958
 
        assert revision.startswith('tag:')
959
 
        raise BzrError('tag: namespace registered, but not implemented.')
960
 
    REVISION_NAMESPACES['tag:'] = _namespace_tag
961
 
 
962
 
    def _namespace_date(self, revs, revision):
963
 
        assert revision.startswith('date:')
964
 
        import datetime
965
 
        # Spec for date revisions:
966
 
        #   date:value
967
 
        #   value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
968
 
        #   it can also start with a '+/-/='. '+' says match the first
969
 
        #   entry after the given date. '-' is match the first entry before the date
970
 
        #   '=' is match the first entry after, but still on the given date.
971
 
        #
972
 
        #   +2005-05-12 says find the first matching entry after May 12th, 2005 at 0:00
973
 
        #   -2005-05-12 says find the first matching entry before May 12th, 2005 at 0:00
974
 
        #   =2005-05-12 says find the first match after May 12th, 2005 at 0:00 but before
975
 
        #       May 13th, 2005 at 0:00
976
 
        #
977
 
        #   So the proper way of saying 'give me all entries for today' is:
978
 
        #       -r {date:+today}:{date:-tomorrow}
979
 
        #   The default is '=' when not supplied
980
 
        val = revision[5:]
981
 
        match_style = '='
982
 
        if val[:1] in ('+', '-', '='):
983
 
            match_style = val[:1]
984
 
            val = val[1:]
985
 
 
986
 
        today = datetime.datetime.today().replace(hour=0,minute=0,second=0,microsecond=0)
987
 
        if val.lower() == 'yesterday':
988
 
            dt = today - datetime.timedelta(days=1)
989
 
        elif val.lower() == 'today':
990
 
            dt = today
991
 
        elif val.lower() == 'tomorrow':
992
 
            dt = today + datetime.timedelta(days=1)
993
 
        else:
994
 
            import re
995
 
            # This should be done outside the function to avoid recompiling it.
996
 
            _date_re = re.compile(
997
 
                    r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
998
 
                    r'(,|T)?\s*'
999
 
                    r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
1000
 
                )
1001
 
            m = _date_re.match(val)
1002
 
            if not m or (not m.group('date') and not m.group('time')):
1003
 
                raise BzrError('Invalid revision date %r' % revision)
1004
 
 
1005
 
            if m.group('date'):
1006
 
                year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
1007
 
            else:
1008
 
                year, month, day = today.year, today.month, today.day
1009
 
            if m.group('time'):
1010
 
                hour = int(m.group('hour'))
1011
 
                minute = int(m.group('minute'))
1012
 
                if m.group('second'):
1013
 
                    second = int(m.group('second'))
1014
 
                else:
1015
 
                    second = 0
1016
 
            else:
1017
 
                hour, minute, second = 0,0,0
1018
 
 
1019
 
            dt = datetime.datetime(year=year, month=month, day=day,
1020
 
                    hour=hour, minute=minute, second=second)
1021
 
        first = dt
1022
 
        last = None
1023
 
        reversed = False
1024
 
        if match_style == '-':
1025
 
            reversed = True
1026
 
        elif match_style == '=':
1027
 
            last = dt + datetime.timedelta(days=1)
1028
 
 
1029
 
        if reversed:
1030
 
            for i in range(len(revs)-1, -1, -1):
1031
 
                r = self.get_revision(revs[i])
1032
 
                # TODO: Handle timezone.
1033
 
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1034
 
                if first >= dt and (last is None or dt >= last):
1035
 
                    return i+1
1036
 
        else:
1037
 
            for i in range(len(revs)):
1038
 
                r = self.get_revision(revs[i])
1039
 
                # TODO: Handle timezone.
1040
 
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1041
 
                if first <= dt and (last is None or dt <= last):
1042
 
                    return i+1
1043
 
    REVISION_NAMESPACES['date:'] = _namespace_date
 
910
    def get_rev_id(self, revno, history=None):
 
911
        """Find the revision id of the specified revno."""
 
912
        if revno == 0:
 
913
            return None
 
914
        if history is None:
 
915
            history = self.revision_history()
 
916
        elif revno <= 0 or revno > len(history):
 
917
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
918
        return history[revno - 1]
 
919
 
1044
920
 
1045
921
    def revision_tree(self, revision_id):
1046
922
        """Return Tree for a revision on this branch.
1058
934
 
1059
935
    def working_tree(self):
1060
936
        """Return a `Tree` for the working copy."""
1061
 
        from workingtree import WorkingTree
 
937
        from bzrlib.workingtree import WorkingTree
1062
938
        return WorkingTree(self.base, self.read_working_inventory())
1063
939
 
1064
940
 
1113
989
            from_abs = self.abspath(from_rel)
1114
990
            to_abs = self.abspath(to_rel)
1115
991
            try:
1116
 
                os.rename(from_abs, to_abs)
 
992
                rename(from_abs, to_abs)
1117
993
            except OSError, e:
1118
994
                raise BzrError("failed to rename %r to %r: %s"
1119
995
                        % (from_abs, to_abs, e[1]),
1182
1058
                result.append((f, dest_path))
1183
1059
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1184
1060
                try:
1185
 
                    os.rename(self.abspath(f), self.abspath(dest_path))
 
1061
                    rename(self.abspath(f), self.abspath(dest_path))
1186
1062
                except OSError, e:
1187
1063
                    raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1188
1064
                            ["rename rolled back"])
1280
1156
            self.unlock()
1281
1157
 
1282
1158
 
1283
 
 
1284
 
class ScratchBranch(Branch):
 
1159
    def get_parent(self):
 
1160
        """Return the parent location of the branch.
 
1161
 
 
1162
        This is the default location for push/pull/missing.  The usual
 
1163
        pattern is that the user can override it by specifying a
 
1164
        location.
 
1165
        """
 
1166
        import errno
 
1167
        _locs = ['parent', 'pull', 'x-pull']
 
1168
        for l in _locs:
 
1169
            try:
 
1170
                return self.controlfile(l, 'r').read().strip('\n')
 
1171
            except IOError, e:
 
1172
                if e.errno != errno.ENOENT:
 
1173
                    raise
 
1174
        return None
 
1175
 
 
1176
 
 
1177
    def set_parent(self, url):
 
1178
        # TODO: Maybe delete old location files?
 
1179
        from bzrlib.atomicfile import AtomicFile
 
1180
        self.lock_write()
 
1181
        try:
 
1182
            f = AtomicFile(self.controlfilename('parent'))
 
1183
            try:
 
1184
                f.write(url + '\n')
 
1185
                f.commit()
 
1186
            finally:
 
1187
                f.close()
 
1188
        finally:
 
1189
            self.unlock()
 
1190
 
 
1191
    def check_revno(self, revno):
 
1192
        """\
 
1193
        Check whether a revno corresponds to any revision.
 
1194
        Zero (the NULL revision) is considered valid.
 
1195
        """
 
1196
        if revno != 0:
 
1197
            self.check_real_revno(revno)
 
1198
            
 
1199
    def check_real_revno(self, revno):
 
1200
        """\
 
1201
        Check whether a revno corresponds to a real revision.
 
1202
        Zero (the NULL revision) is considered invalid
 
1203
        """
 
1204
        if revno < 1 or revno > self.revno():
 
1205
            raise InvalidRevisionNumber(revno)
 
1206
        
 
1207
        
 
1208
        
 
1209
 
 
1210
 
 
1211
class ScratchBranch(LocalBranch):
1285
1212
    """Special test class: a branch that cleans up after itself.
1286
1213
 
1287
1214
    >>> b = ScratchBranch()
1304
1231
        if base is None:
1305
1232
            base = mkdtemp()
1306
1233
            init = True
1307
 
        Branch.__init__(self, base, init=init)
 
1234
        LocalBranch.__init__(self, base, init=init)
1308
1235
        for d in dirs:
1309
1236
            os.mkdir(self.abspath(d))
1310
1237
            
1316
1243
        """
1317
1244
        >>> orig = ScratchBranch(files=["file1", "file2"])
1318
1245
        >>> clone = orig.clone()
1319
 
        >>> os.path.samefile(orig.base, clone.base)
 
1246
        >>> if os.name != 'nt':
 
1247
        ...   os.path.samefile(orig.base, clone.base)
 
1248
        ... else:
 
1249
        ...   orig.base == clone.base
 
1250
        ...
1320
1251
        False
1321
1252
        >>> os.path.isfile(os.path.join(clone.base, "file1"))
1322
1253
        True
1327
1258
        os.rmdir(base)
1328
1259
        copytree(self.base, base, symlinks=True)
1329
1260
        return ScratchBranch(base=base)
 
1261
 
 
1262
 
1330
1263
        
1331
1264
    def __del__(self):
1332
1265
        self.destroy()
1403
1336
    return gen_file_id('TREE_ROOT')
1404
1337
 
1405
1338
 
1406
 
def pull_loc(branch):
1407
 
    # TODO: Should perhaps just make attribute be 'base' in
1408
 
    # RemoteBranch and Branch?
1409
 
    if hasattr(branch, "baseurl"):
1410
 
        return branch.baseurl
1411
 
    else:
1412
 
        return branch.base
1413
 
 
1414
 
 
1415
 
def copy_branch(branch_from, to_location, revision=None):
 
1339
def copy_branch(branch_from, to_location, revno=None):
1416
1340
    """Copy branch_from into the existing directory to_location.
1417
1341
 
1418
 
    If revision is not None, the head of the new branch will be revision.
 
1342
    revision
 
1343
        If not None, only revisions up to this point will be copied.
 
1344
        The head of the new branch will be that revision.
 
1345
 
 
1346
    to_location
 
1347
        The name of a local directory that exists but is empty.
1419
1348
    """
1420
1349
    from bzrlib.merge import merge
1421
 
    from bzrlib.branch import Branch
1422
 
    br_to = Branch(to_location, init=True)
 
1350
 
 
1351
    assert isinstance(branch_from, Branch)
 
1352
    assert isinstance(to_location, basestring)
 
1353
    
 
1354
    br_to = Branch.initialize(to_location)
1423
1355
    br_to.set_root_id(branch_from.get_root_id())
1424
 
    if revision is None:
 
1356
    if revno is None:
1425
1357
        revno = branch_from.revno()
1426
 
    else:
1427
 
        revno, rev_id = branch_from.get_revision_info(revision)
1428
1358
    br_to.update_revisions(branch_from, stop_revision=revno)
1429
1359
    merge((to_location, -1), (to_location, 0), this_dir=to_location,
1430
1360
          check_clean=False, ignore_zero=True)
1431
 
    from_location = pull_loc(branch_from)
1432
 
    br_to.controlfile("x-pull", "wb").write(from_location + "\n")
1433
 
 
 
1361
    br_to.set_parent(branch_from.base)
 
1362
    return br_to