/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 01:41:00 UTC
  • Revision ID: mbp@sourcefrog.net-20050913014100-1385f2cc25d9259f
- comment out tests that don't pass with weave storage at the moment

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
 
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId
27
 
import bzrlib.errors
 
26
 
 
27
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
 
28
                           NoSuchRevision)
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
 
        
34
 
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
 
33
from bzrlib.inventory import Inventory
 
34
from bzrlib.weavestore import WeaveStore
 
35
import bzrlib.xml5
 
36
import bzrlib.ui
 
37
 
 
38
 
 
39
 
 
40
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
 
41
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
35
42
## TODO: Maybe include checks for common corruption of newlines, etc?
36
43
 
37
44
 
39
46
# repeatedly to calculate deltas.  We could perhaps have a weakref
40
47
# cache in memory to make this faster.
41
48
 
 
49
# TODO: please move the revision-string syntax stuff out of the branch
 
50
# object; it's clutter
 
51
 
42
52
 
43
53
def find_branch(f, **args):
44
54
    if f and (f.startswith('http://') or f.startswith('https://')):
101
111
    It is not necessary that f exists.
102
112
 
103
113
    Basically we keep looking up until we find the control directory or
104
 
    run into the root."""
 
114
    run into the root.  If there isn't one, raises NotBranchError.
 
115
    """
105
116
    if f == None:
106
117
        f = os.getcwd()
107
118
    elif hasattr(os.path, 'realpath'):
120
131
        head, tail = os.path.split(f)
121
132
        if head == f:
122
133
            # reached the root, whatever that may be
123
 
            raise BzrError('%r is not in a branch' % orig_f)
 
134
            raise bzrlib.errors.NotBranchError('%s is not in a branch' % orig_f)
124
135
        f = head
125
 
    
 
136
 
 
137
 
 
138
 
 
139
# XXX: move into bzrlib.errors; subclass BzrError    
126
140
class DivergedBranches(Exception):
127
141
    def __init__(self, branch1, branch2):
128
142
        self.branch1 = branch1
189
203
                                      'current bzr can only operate from top-of-tree'])
190
204
        self._check_format()
191
205
 
192
 
        self.text_store = ImmutableStore(self.controlfilename('text-store'))
 
206
        self.weave_store = WeaveStore(self.controlfilename('weaves'))
193
207
        self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
194
208
        self.inventory_store = ImmutableStore(self.controlfilename('inventory-store'))
195
209
 
208
222
            self._lock.unlock()
209
223
 
210
224
 
211
 
 
212
225
    def lock_write(self):
213
226
        if self._lock_mode:
214
227
            if self._lock_mode != 'w':
224
237
            self._lock_count = 1
225
238
 
226
239
 
227
 
 
228
240
    def lock_read(self):
229
241
        if self._lock_mode:
230
242
            assert self._lock_mode in ('r', 'w'), \
237
249
            self._lock_mode = 'r'
238
250
            self._lock_count = 1
239
251
                        
240
 
 
241
 
            
242
252
    def unlock(self):
243
253
        if not self._lock_mode:
244
254
            from errors import LockError
251
261
            self._lock = None
252
262
            self._lock_mode = self._lock_count = None
253
263
 
254
 
 
255
264
    def abspath(self, name):
256
265
        """Return absolute filename for something in the branch"""
257
266
        return os.path.join(self.base, name)
258
267
 
259
 
 
260
268
    def relpath(self, path):
261
269
        """Return path relative to this branch of something inside it.
262
270
 
263
271
        Raises an error if path is not in this branch."""
264
272
        return _relpath(self.base, path)
265
273
 
266
 
 
267
274
    def controlfilename(self, file_or_path):
268
275
        """Return location relative to branch."""
269
276
        if isinstance(file_or_path, basestring):
296
303
        else:
297
304
            raise BzrError("invalid controlfile mode %r" % mode)
298
305
 
299
 
 
300
 
 
301
306
    def _make_control(self):
302
 
        from bzrlib.inventory import Inventory
303
 
        from bzrlib.xml import pack_xml
304
 
        
305
307
        os.mkdir(self.controlfilename([]))
306
308
        self.controlfile('README', 'w').write(
307
309
            "This is a Bazaar-NG control directory.\n"
308
310
            "Do not change any files in this directory.\n")
309
 
        self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT)
310
 
        for d in ('text-store', 'inventory-store', 'revision-store'):
 
311
        self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT_5)
 
312
        for d in ('text-store', 'inventory-store', 'revision-store',
 
313
                  'weaves'):
311
314
            os.mkdir(self.controlfilename(d))
312
315
        for f in ('revision-history', 'merged-patches',
313
316
                  'pending-merged-patches', 'branch-name',
316
319
            self.controlfile(f, 'w').write('')
317
320
        mutter('created control directory in ' + self.base)
318
321
 
319
 
        pack_xml(Inventory(gen_root_id()), self.controlfile('inventory','w'))
 
322
        # if we want per-tree root ids then this is the place to set
 
323
        # them; they're not needed for now and so ommitted for
 
324
        # simplicity.
 
325
        f = self.controlfile('inventory','w')
 
326
        bzrlib.xml5.serializer_v5.write_inventory(Inventory(), f)
320
327
 
321
328
 
322
329
    def _check_format(self):
323
330
        """Check this branch format is supported.
324
331
 
325
 
        The current tool only supports the current unstable format.
 
332
        The format level is stored, as an integer, in
 
333
        self._branch_format for code that needs to check it later.
326
334
 
327
335
        In the future, we might need different in-memory Branch
328
336
        classes to support downlevel branches.  But not yet.
329
337
        """
330
 
        # This ignores newlines so that we can open branches created
331
 
        # on Windows from Linux and so on.  I think it might be better
332
 
        # to always make all internal files in unix format.
333
338
        fmt = self.controlfile('branch-format', 'r').read()
334
 
        fmt.replace('\r\n', '')
335
 
        if fmt != BZR_BRANCH_FORMAT:
336
 
            raise BzrError('sorry, branch format %r not supported' % fmt,
337
 
                           ['use a different bzr version',
338
 
                            'or remove the .bzr directory and "bzr init" again'])
 
339
        if fmt == BZR_BRANCH_FORMAT_5:
 
340
            self._branch_format = 5
 
341
        else:
 
342
            raise BzrError('sorry, branch format "%s" not supported; ' 
 
343
                           'use a different bzr version, '
 
344
                           'or run "bzr upgrade", '
 
345
                           'or remove the .bzr directory and "bzr init" again'
 
346
                           % fmt.rstrip('\n\r'))
339
347
 
340
348
    def get_root_id(self):
341
349
        """Return the id of this branches root"""
356
364
 
357
365
    def read_working_inventory(self):
358
366
        """Read the working inventory."""
359
 
        from bzrlib.inventory import Inventory
360
 
        from bzrlib.xml import unpack_xml
361
 
        from time import time
362
 
        before = time()
363
367
        self.lock_read()
364
368
        try:
365
369
            # ElementTree does its own conversion from UTF-8, so open in
366
370
            # 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
 
371
            f = self.controlfile('inventory', 'rb')
 
372
            return bzrlib.xml5.serializer_v5.read_inventory(f)
372
373
        finally:
373
374
            self.unlock()
374
375
            
380
381
        will be committed to the next revision.
381
382
        """
382
383
        from bzrlib.atomicfile import AtomicFile
383
 
        from bzrlib.xml import pack_xml
384
384
        
385
385
        self.lock_write()
386
386
        try:
387
387
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
388
388
            try:
389
 
                pack_xml(inv, f)
 
389
                bzrlib.xml5.serializer_v5.write_inventory(inv, f)
390
390
                f.commit()
391
391
            finally:
392
392
                f.close()
400
400
                         """Inventory for the working copy.""")
401
401
 
402
402
 
403
 
    def add(self, files, verbose=False, ids=None):
 
403
    def add(self, files, ids=None):
404
404
        """Make files versioned.
405
405
 
406
 
        Note that the command line normally calls smart_add instead.
 
406
        Note that the command line normally calls smart_add instead,
 
407
        which can automatically recurse.
407
408
 
408
409
        This puts the files in the Added state, so that they will be
409
410
        recorded by the next commit.
419
420
        TODO: Perhaps have an option to add the ids even if the files do
420
421
              not (yet) exist.
421
422
 
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.
 
423
        TODO: Perhaps yield the ids and paths as they're added.
428
424
        """
429
425
        # TODO: Re-adding a file that is removed in the working copy
430
426
        # should probably put it back with the previous ID.
466
462
                    file_id = gen_file_id(f)
467
463
                inv.add_path(f, kind=kind, file_id=file_id)
468
464
 
469
 
                if verbose:
470
 
                    print 'added', quotefn(f)
471
 
 
472
465
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
473
466
 
474
467
            self._write_inventory(inv)
584
577
            f.close()
585
578
 
586
579
 
587
 
    def get_revision_xml(self, revision_id):
 
580
    def get_revision_xml_file(self, revision_id):
588
581
        """Return XML file object for revision object."""
589
582
        if not revision_id or not isinstance(revision_id, basestring):
590
583
            raise InvalidRevisionId(revision_id)
594
587
            try:
595
588
                return self.revision_store[revision_id]
596
589
            except IndexError:
597
 
                raise bzrlib.errors.NoSuchRevision(revision_id)
 
590
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
598
591
        finally:
599
592
            self.unlock()
600
593
 
601
594
 
 
595
    #deprecated
 
596
    get_revision_xml = get_revision_xml_file
 
597
 
 
598
 
602
599
    def get_revision(self, revision_id):
603
600
        """Return the Revision object for a named revision"""
604
 
        xml_file = self.get_revision_xml(revision_id)
 
601
        xml_file = self.get_revision_xml_file(revision_id)
605
602
 
606
603
        try:
607
 
            r = unpack_xml(Revision, xml_file)
 
604
            r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
608
605
        except SyntaxError, e:
609
606
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
610
607
                                         [revision_id,
648
645
        return bzrlib.osutils.sha_file(self.get_revision_xml(revision_id))
649
646
 
650
647
 
651
 
    def get_inventory(self, inventory_id):
 
648
    def get_inventory(self, revision_id):
652
649
        """Get Inventory object by hash.
653
650
 
654
651
        TODO: Perhaps for this and similar methods, take a revision
655
652
               parameter which can be either an integer revno or a
656
653
               string hash."""
657
 
        from bzrlib.inventory import Inventory
658
 
        from bzrlib.xml import unpack_xml
659
 
 
660
 
        return unpack_xml(Inventory, self.inventory_store[inventory_id])
 
654
        f = self.get_inventory_xml_file(revision_id)
 
655
        return bzrlib.xml5.serializer_v5.read_inventory(f)
 
656
 
 
657
 
 
658
    def get_inventory_xml(self, revision_id):
 
659
        """Get inventory XML as a file object."""
 
660
        try:
 
661
            assert isinstance(revision_id, basestring), type(revision_id)
 
662
            return self.inventory_store[revision_id]
 
663
        except IndexError:
 
664
            raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
 
665
 
 
666
    get_inventory_xml_file = get_inventory_xml
661
667
            
662
668
 
663
 
    def get_inventory_sha1(self, inventory_id):
 
669
    def get_inventory_sha1(self, revision_id):
664
670
        """Return the sha1 hash of the inventory entry
665
671
        """
666
 
        return sha_file(self.inventory_store[inventory_id])
 
672
        return sha_file(self.get_inventory_xml_file(revision_id))
667
673
 
668
674
 
669
675
    def get_revision_inventory(self, revision_id):
670
676
        """Return inventory of a past revision."""
671
 
        # bzr 0.0.6 imposes the constraint that the inventory_id
 
677
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
672
678
        # must be the same as its revision, so this is trivial.
673
679
        if revision_id == None:
674
 
            from bzrlib.inventory import Inventory
675
680
            return Inventory(self.get_root_id())
676
681
        else:
677
682
            return self.get_inventory(revision_id)
697
702
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
698
703
        >>> sb.common_ancestor(sb) == (None, None)
699
704
        True
700
 
        >>> commit.commit(sb, "Committing first revision", verbose=False)
 
705
        >>> commit.commit(sb, "Committing first revision")
701
706
        >>> sb.common_ancestor(sb)[0]
702
707
        1
703
708
        >>> clone = sb.clone()
704
 
        >>> commit.commit(sb, "Committing second revision", verbose=False)
 
709
        >>> commit.commit(sb, "Committing second revision")
705
710
        >>> sb.common_ancestor(sb)[0]
706
711
        2
707
712
        >>> sb.common_ancestor(clone)[0]
708
713
        1
709
 
        >>> commit.commit(clone, "Committing divergent second revision", 
710
 
        ...               verbose=False)
 
714
        >>> commit.commit(clone, "Committing divergent second revision")
711
715
        >>> sb.common_ancestor(clone)[0]
712
716
        1
713
717
        >>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
755
759
            return None
756
760
 
757
761
 
758
 
    def missing_revisions(self, other, stop_revision=None):
 
762
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
759
763
        """
760
764
        If self and other have not diverged, return a list of the revisions
761
765
        present in other, but missing from self.
794
798
        if stop_revision is None:
795
799
            stop_revision = other_len
796
800
        elif stop_revision > other_len:
797
 
            raise NoSuchRevision(self, stop_revision)
 
801
            raise bzrlib.errors.NoSuchRevision(self, stop_revision)
798
802
        
799
803
        return other_history[self_len:stop_revision]
800
804
 
801
805
 
802
806
    def update_revisions(self, other, stop_revision=None):
803
807
        """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
808
        """
825
 
        from bzrlib.progress import ProgressBar
826
 
 
827
 
        pb = ProgressBar()
828
 
 
 
809
        from bzrlib.fetch import greedy_fetch
 
810
 
 
811
        pb = bzrlib.ui.ui_factory.progress_bar()
829
812
        pb.update('comparing histories')
 
813
 
830
814
        revision_ids = self.missing_revisions(other, stop_revision)
831
815
 
832
 
        if hasattr(other.revision_store, "prefetch"):
833
 
            other.revision_store.prefetch(revision_ids)
834
 
        if hasattr(other.inventory_store, "prefetch"):
835
 
            inventory_ids = [other.get_revision(r).inventory_id
836
 
                             for r in revision_ids]
837
 
            other.inventory_store.prefetch(inventory_ids)
838
 
                
839
 
        revisions = []
840
 
        needed_texts = set()
841
 
        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)
846
 
            revisions.append(rev)
847
 
            inv = other.get_inventory(str(rev.inventory_id))
848
 
            for key, entry in inv.iter_entries():
849
 
                if entry.text_id is None:
850
 
                    continue
851
 
                if entry.text_id not in self.text_store:
852
 
                    needed_texts.add(entry.text_id)
853
 
 
 
816
        if len(revision_ids) > 0:
 
817
            count = greedy_fetch(self, other, revision_ids[-1], pb)[0]
 
818
        else:
 
819
            count = 0
 
820
        self.append_revision(*revision_ids)
 
821
        ## note("Added %d revisions." % count)
854
822
        pb.clear()
855
 
                    
856
 
        count = self.text_store.copy_multi(other.text_store, needed_texts)
857
 
        print "Added %d texts." % count 
858
 
        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 
862
 
        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
 
        
 
823
 
 
824
 
870
825
    def commit(self, *args, **kw):
871
 
        from bzrlib.commit import commit
872
 
        commit(self, *args, **kw)
 
826
        from bzrlib.commit import Commit
 
827
        Commit().commit(self, *args, **kw)
873
828
        
874
829
 
875
830
    def lookup_revision(self, revision):
876
831
        """Return the revision identifier for a given revision information."""
877
 
        revno, info = self.get_revision_info(revision)
 
832
        revno, info = self._get_revision_info(revision)
878
833
        return info
879
834
 
 
835
 
 
836
    def revision_id_to_revno(self, revision_id):
 
837
        """Given a revision id, return its revno"""
 
838
        history = self.revision_history()
 
839
        try:
 
840
            return history.index(revision_id) + 1
 
841
        except ValueError:
 
842
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
843
 
 
844
 
880
845
    def get_revision_info(self, revision):
881
846
        """Return (revno, revision id) for revision identifier.
882
847
 
885
850
        revision can also be a string, in which case it is parsed for something like
886
851
            'date:' or 'revid:' etc.
887
852
        """
 
853
        revno, rev_id = self._get_revision_info(revision)
 
854
        if revno is None:
 
855
            raise bzrlib.errors.NoSuchRevision(self, revision)
 
856
        return revno, rev_id
 
857
 
 
858
    def get_rev_id(self, revno, history=None):
 
859
        """Find the revision id of the specified revno."""
 
860
        if revno == 0:
 
861
            return None
 
862
        if history is None:
 
863
            history = self.revision_history()
 
864
        elif revno <= 0 or revno > len(history):
 
865
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
866
        return history[revno - 1]
 
867
 
 
868
    def _get_revision_info(self, revision):
 
869
        """Return (revno, revision id) for revision specifier.
 
870
 
 
871
        revision can be an integer, in which case it is assumed to be revno
 
872
        (though this will translate negative values into positive ones)
 
873
        revision can also be a string, in which case it is parsed for something
 
874
        like 'date:' or 'revid:' etc.
 
875
 
 
876
        A revid is always returned.  If it is None, the specifier referred to
 
877
        the null revision.  If the revid does not occur in the revision
 
878
        history, revno will be None.
 
879
        """
 
880
        
888
881
        if revision is None:
889
882
            return 0, None
890
883
        revno = None
894
887
            pass
895
888
        revs = self.revision_history()
896
889
        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
890
            if revision < 0:
901
891
                revno = len(revs) + revision + 1
902
892
            else:
903
893
                revno = revision
 
894
            rev_id = self.get_rev_id(revno, revs)
904
895
        elif isinstance(revision, basestring):
905
896
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
906
897
                if revision.startswith(prefix):
907
 
                    revno = func(self, revs, revision)
 
898
                    result = func(self, revs, revision)
 
899
                    if len(result) > 1:
 
900
                        revno, rev_id = result
 
901
                    else:
 
902
                        revno = result[0]
 
903
                        rev_id = self.get_rev_id(revno, revs)
908
904
                    break
909
905
            else:
910
 
                raise BzrError('No namespace registered for string: %r' % revision)
 
906
                raise BzrError('No namespace registered for string: %r' %
 
907
                               revision)
 
908
        else:
 
909
            raise TypeError('Unhandled revision type %s' % revision)
911
910
 
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]
 
911
        if revno is None:
 
912
            if rev_id is None:
 
913
                raise bzrlib.errors.NoSuchRevision(self, revision)
 
914
        return revno, rev_id
915
915
 
916
916
    def _namespace_revno(self, revs, revision):
917
917
        """Lookup a revision by revision number"""
918
918
        assert revision.startswith('revno:')
919
919
        try:
920
 
            return int(revision[6:])
 
920
            return (int(revision[6:]),)
921
921
        except ValueError:
922
922
            return None
923
923
    REVISION_NAMESPACES['revno:'] = _namespace_revno
924
924
 
925
925
    def _namespace_revid(self, revs, revision):
926
926
        assert revision.startswith('revid:')
 
927
        rev_id = revision[len('revid:'):]
927
928
        try:
928
 
            return revs.index(revision[6:]) + 1
 
929
            return revs.index(rev_id) + 1, rev_id
929
930
        except ValueError:
930
 
            return None
 
931
            return None, rev_id
931
932
    REVISION_NAMESPACES['revid:'] = _namespace_revid
932
933
 
933
934
    def _namespace_last(self, revs, revision):
935
936
        try:
936
937
            offset = int(revision[5:])
937
938
        except ValueError:
938
 
            return None
 
939
            return (None,)
939
940
        else:
940
941
            if offset <= 0:
941
942
                raise BzrError('You must supply a positive value for --revision last:XXX')
942
 
            return len(revs) - offset + 1
 
943
            return (len(revs) - offset + 1,)
943
944
    REVISION_NAMESPACES['last:'] = _namespace_last
944
945
 
945
946
    def _namespace_tag(self, revs, revision):
1020
1021
                # TODO: Handle timezone.
1021
1022
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1022
1023
                if first >= dt and (last is None or dt >= last):
1023
 
                    return i+1
 
1024
                    return (i+1,)
1024
1025
        else:
1025
1026
            for i in range(len(revs)):
1026
1027
                r = self.get_revision(revs[i])
1027
1028
                # TODO: Handle timezone.
1028
1029
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1029
1030
                if first <= dt and (last is None or dt <= last):
1030
 
                    return i+1
 
1031
                    return (i+1,)
1031
1032
    REVISION_NAMESPACES['date:'] = _namespace_date
1032
1033
 
1033
1034
    def revision_tree(self, revision_id):
1041
1042
            return EmptyTree()
1042
1043
        else:
1043
1044
            inv = self.get_revision_inventory(revision_id)
1044
 
            return RevisionTree(self.text_store, inv)
 
1045
            return RevisionTree(self.weave_store, inv, revision_id)
1045
1046
 
1046
1047
 
1047
1048
    def working_tree(self):
1055
1056
 
1056
1057
        If there are no revisions yet, return an `EmptyTree`.
1057
1058
        """
1058
 
        r = self.last_patch()
1059
 
        if r == None:
1060
 
            return EmptyTree()
1061
 
        else:
1062
 
            return RevisionTree(self.text_store, self.get_revision_inventory(r))
1063
 
 
 
1059
        return self.revision_tree(self.last_patch())
1064
1060
 
1065
1061
 
1066
1062
    def rename_one(self, from_rel, to_rel):
1098
1094
 
1099
1095
            inv.rename(file_id, to_dir_id, to_tail)
1100
1096
 
1101
 
            print "%s => %s" % (from_rel, to_rel)
1102
 
 
1103
1097
            from_abs = self.abspath(from_rel)
1104
1098
            to_abs = self.abspath(to_rel)
1105
1099
            try:
1124
1118
 
1125
1119
        Note that to_name is only the last component of the new name;
1126
1120
        this doesn't change the directory.
 
1121
 
 
1122
        This returns a list of (from_path, to_path) pairs for each
 
1123
        entry that is moved.
1127
1124
        """
 
1125
        result = []
1128
1126
        self.lock_write()
1129
1127
        try:
1130
1128
            ## TODO: Option to move IDs only
1165
1163
            for f in from_paths:
1166
1164
                name_tail = splitpath(f)[-1]
1167
1165
                dest_path = appendpath(to_name, name_tail)
1168
 
                print "%s => %s" % (f, dest_path)
 
1166
                result.append((f, dest_path))
1169
1167
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1170
1168
                try:
1171
1169
                    os.rename(self.abspath(f), self.abspath(dest_path))
1177
1175
        finally:
1178
1176
            self.unlock()
1179
1177
 
 
1178
        return result
 
1179
 
1180
1180
 
1181
1181
    def revert(self, filenames, old_tree=None, backups=True):
1182
1182
        """Restore selected files to the versions from a previous tree.
1264
1264
            self.unlock()
1265
1265
 
1266
1266
 
 
1267
    def get_parent(self):
 
1268
        """Return the parent location of the branch.
 
1269
 
 
1270
        This is the default location for push/pull/missing.  The usual
 
1271
        pattern is that the user can override it by specifying a
 
1272
        location.
 
1273
        """
 
1274
        import errno
 
1275
        _locs = ['parent', 'pull', 'x-pull']
 
1276
        for l in _locs:
 
1277
            try:
 
1278
                return self.controlfile(l, 'r').read().strip('\n')
 
1279
            except IOError, e:
 
1280
                if e.errno != errno.ENOENT:
 
1281
                    raise
 
1282
        return None
 
1283
 
 
1284
 
 
1285
    def set_parent(self, url):
 
1286
        # TODO: Maybe delete old location files?
 
1287
        from bzrlib.atomicfile import AtomicFile
 
1288
        self.lock_write()
 
1289
        try:
 
1290
            f = AtomicFile(self.controlfilename('parent'))
 
1291
            try:
 
1292
                f.write(url + '\n')
 
1293
                f.commit()
 
1294
            finally:
 
1295
                f.close()
 
1296
        finally:
 
1297
            self.unlock()
 
1298
 
 
1299
    def check_revno(self, revno):
 
1300
        """\
 
1301
        Check whether a revno corresponds to any revision.
 
1302
        Zero (the NULL revision) is considered valid.
 
1303
        """
 
1304
        if revno != 0:
 
1305
            self.check_real_revno(revno)
 
1306
            
 
1307
    def check_real_revno(self, revno):
 
1308
        """\
 
1309
        Check whether a revno corresponds to a real revision.
 
1310
        Zero (the NULL revision) is considered invalid
 
1311
        """
 
1312
        if revno < 1 or revno > self.revno():
 
1313
            raise InvalidRevisionNumber(revno)
 
1314
        
 
1315
        
 
1316
 
1267
1317
 
1268
1318
class ScratchBranch(Branch):
1269
1319
    """Special test class: a branch that cleans up after itself.
1311
1361
        os.rmdir(base)
1312
1362
        copytree(self.base, base, symlinks=True)
1313
1363
        return ScratchBranch(base=base)
 
1364
 
 
1365
 
1314
1366
        
1315
1367
    def __del__(self):
1316
1368
        self.destroy()
1386
1438
    """Return a new tree-root file id."""
1387
1439
    return gen_file_id('TREE_ROOT')
1388
1440
 
 
1441
 
 
1442
def pull_loc(branch):
 
1443
    # TODO: Should perhaps just make attribute be 'base' in
 
1444
    # RemoteBranch and Branch?
 
1445
    if hasattr(branch, "baseurl"):
 
1446
        return branch.baseurl
 
1447
    else:
 
1448
        return branch.base
 
1449
 
 
1450
 
 
1451
def copy_branch(branch_from, to_location, revision=None):
 
1452
    """Copy branch_from into the existing directory to_location.
 
1453
 
 
1454
    revision
 
1455
        If not None, only revisions up to this point will be copied.
 
1456
        The head of the new branch will be that revision.
 
1457
 
 
1458
    to_location
 
1459
        The name of a local directory that exists but is empty.
 
1460
    """
 
1461
    from bzrlib.merge import merge
 
1462
    from bzrlib.branch import Branch
 
1463
 
 
1464
    assert isinstance(branch_from, Branch)
 
1465
    assert isinstance(to_location, basestring)
 
1466
    
 
1467
    br_to = Branch(to_location, init=True)
 
1468
    br_to.set_root_id(branch_from.get_root_id())
 
1469
    if revision is None:
 
1470
        revno = branch_from.revno()
 
1471
    else:
 
1472
        revno, rev_id = branch_from.get_revision_info(revision)
 
1473
    br_to.update_revisions(branch_from, stop_revision=revno)
 
1474
    merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
1475
          check_clean=False, ignore_zero=True)
 
1476
    
 
1477
    from_location = pull_loc(branch_from)
 
1478
    br_to.set_parent(pull_loc(branch_from))
 
1479