/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: Lalo Martins
  • Date: 2005-09-07 10:50:03 UTC
  • mto: (1185.1.5)
  • mto: This revision was merged to the branch mainline in revision 1390.
  • Revision ID: lalo@exoweb.net-20050907105002-4e37d43b7d4060fe
unifying 'base' (from Branch) and 'baseurl' (from RemoteBranch) attributes;
this allows us to remove quite a few "dead chickens" from the code.

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
     DivergedBranches, NotBranchError
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://')):
45
 
        import remotebranch 
46
 
        return remotebranch.RemoteBranch(f, **args)
 
52
        from bzrlib.remotebranch import RemoteBranch
 
53
        return RemoteBranch(f, **args)
47
54
    else:
48
55
        return Branch(f, **args)
49
56
 
50
57
 
51
58
def find_cached_branch(f, cache_root, **args):
52
 
    from remotebranch import RemoteBranch
 
59
    from bzrlib.remotebranch import RemoteBranch
53
60
    br = find_branch(f, **args)
54
61
    def cacheify(br, store_name):
55
 
        from meta_store import CachedStore
 
62
        from bzrlib.meta_store import CachedStore
56
63
        cache_path = os.path.join(cache_root, store_name)
57
64
        os.mkdir(cache_path)
58
65
        new_store = CachedStore(getattr(br, store_name), cache_path)
87
94
        if tail:
88
95
            s.insert(0, tail)
89
96
    else:
90
 
        from errors import NotBranchError
91
97
        raise NotBranchError("path %r is not within branch %r" % (rp, base))
92
98
 
93
99
    return os.sep.join(s)
101
107
    It is not necessary that f exists.
102
108
 
103
109
    Basically we keep looking up until we find the control directory or
104
 
    run into the root."""
 
110
    run into the root.  If there isn't one, raises NotBranchError.
 
111
    """
105
112
    if f == None:
106
113
        f = os.getcwd()
107
114
    elif hasattr(os.path, 'realpath'):
120
127
        head, tail = os.path.split(f)
121
128
        if head == f:
122
129
            # reached the root, whatever that may be
123
 
            raise BzrError('%r is not in a branch' % orig_f)
 
130
            raise NotBranchError('%s is not in a branch' % orig_f)
124
131
        f = head
125
 
    
126
 
class DivergedBranches(Exception):
127
 
    def __init__(self, branch1, branch2):
128
 
        self.branch1 = branch1
129
 
        self.branch2 = branch2
130
 
        Exception.__init__(self, "These branches have diverged.")
 
132
 
 
133
 
131
134
 
132
135
 
133
136
######################################################################
183
186
        else:
184
187
            self.base = os.path.realpath(base)
185
188
            if not isdir(self.controlfilename('.')):
186
 
                from errors import NotBranchError
187
189
                raise NotBranchError("not a bzr branch: %s" % quotefn(base),
188
190
                                     ['use "bzr init" to initialize a new working tree',
189
191
                                      'current bzr can only operate from top-of-tree'])
203
205
 
204
206
    def __del__(self):
205
207
        if self._lock_mode or self._lock:
206
 
            from warnings import warn
 
208
            from bzrlib.warnings import warn
207
209
            warn("branch %r was not explicitly unlocked" % self)
208
210
            self._lock.unlock()
209
211
 
210
212
 
211
 
 
212
213
    def lock_write(self):
213
214
        if self._lock_mode:
214
215
            if self._lock_mode != 'w':
215
 
                from errors import LockError
 
216
                from bzrlib.errors import LockError
216
217
                raise LockError("can't upgrade to a write lock from %r" %
217
218
                                self._lock_mode)
218
219
            self._lock_count += 1
224
225
            self._lock_count = 1
225
226
 
226
227
 
227
 
 
228
228
    def lock_read(self):
229
229
        if self._lock_mode:
230
230
            assert self._lock_mode in ('r', 'w'), \
237
237
            self._lock_mode = 'r'
238
238
            self._lock_count = 1
239
239
                        
240
 
 
241
 
            
242
240
    def unlock(self):
243
241
        if not self._lock_mode:
244
 
            from errors import LockError
 
242
            from bzrlib.errors import LockError
245
243
            raise LockError('branch %r is not locked' % (self))
246
244
 
247
245
        if self._lock_count > 1:
251
249
            self._lock = None
252
250
            self._lock_mode = self._lock_count = None
253
251
 
254
 
 
255
252
    def abspath(self, name):
256
253
        """Return absolute filename for something in the branch"""
257
254
        return os.path.join(self.base, name)
258
255
 
259
 
 
260
256
    def relpath(self, path):
261
257
        """Return path relative to this branch of something inside it.
262
258
 
263
259
        Raises an error if path is not in this branch."""
264
260
        return _relpath(self.base, path)
265
261
 
266
 
 
267
262
    def controlfilename(self, file_or_path):
268
263
        """Return location relative to branch."""
269
264
        if isinstance(file_or_path, basestring):
296
291
        else:
297
292
            raise BzrError("invalid controlfile mode %r" % mode)
298
293
 
299
 
 
300
 
 
301
294
    def _make_control(self):
302
295
        from bzrlib.inventory import Inventory
303
 
        from bzrlib.xml import pack_xml
304
296
        
305
297
        os.mkdir(self.controlfilename([]))
306
298
        self.controlfile('README', 'w').write(
316
308
            self.controlfile(f, 'w').write('')
317
309
        mutter('created control directory in ' + self.base)
318
310
 
319
 
        pack_xml(Inventory(gen_root_id()), self.controlfile('inventory','w'))
 
311
        # if we want per-tree root ids then this is the place to set
 
312
        # them; they're not needed for now and so ommitted for
 
313
        # simplicity.
 
314
        f = self.controlfile('inventory','w')
 
315
        bzrlib.xml.serializer_v4.write_inventory(Inventory(), f)
320
316
 
321
317
 
322
318
    def _check_format(self):
331
327
        # on Windows from Linux and so on.  I think it might be better
332
328
        # to always make all internal files in unix format.
333
329
        fmt = self.controlfile('branch-format', 'r').read()
334
 
        fmt.replace('\r\n', '')
 
330
        fmt = fmt.replace('\r\n', '\n')
335
331
        if fmt != BZR_BRANCH_FORMAT:
336
332
            raise BzrError('sorry, branch format %r not supported' % fmt,
337
333
                           ['use a different bzr version',
357
353
    def read_working_inventory(self):
358
354
        """Read the working inventory."""
359
355
        from bzrlib.inventory import Inventory
360
 
        from bzrlib.xml import unpack_xml
361
 
        from time import time
362
 
        before = time()
363
356
        self.lock_read()
364
357
        try:
365
358
            # ElementTree does its own conversion from UTF-8, so open in
366
359
            # 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
 
360
            f = self.controlfile('inventory', 'rb')
 
361
            return bzrlib.xml.serializer_v4.read_inventory(f)
372
362
        finally:
373
363
            self.unlock()
374
364
            
380
370
        will be committed to the next revision.
381
371
        """
382
372
        from bzrlib.atomicfile import AtomicFile
383
 
        from bzrlib.xml import pack_xml
384
373
        
385
374
        self.lock_write()
386
375
        try:
387
376
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
388
377
            try:
389
 
                pack_xml(inv, f)
 
378
                bzrlib.xml.serializer_v4.write_inventory(inv, f)
390
379
                f.commit()
391
380
            finally:
392
381
                f.close()
400
389
                         """Inventory for the working copy.""")
401
390
 
402
391
 
403
 
    def add(self, files, verbose=False, ids=None):
 
392
    def add(self, files, ids=None):
404
393
        """Make files versioned.
405
394
 
406
 
        Note that the command line normally calls smart_add instead.
 
395
        Note that the command line normally calls smart_add instead,
 
396
        which can automatically recurse.
407
397
 
408
398
        This puts the files in the Added state, so that they will be
409
399
        recorded by the next commit.
419
409
        TODO: Perhaps have an option to add the ids even if the files do
420
410
              not (yet) exist.
421
411
 
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.
 
412
        TODO: Perhaps yield the ids and paths as they're added.
428
413
        """
429
414
        # TODO: Re-adding a file that is removed in the working copy
430
415
        # should probably put it back with the previous ID.
466
451
                    file_id = gen_file_id(f)
467
452
                inv.add_path(f, kind=kind, file_id=file_id)
468
453
 
469
 
                if verbose:
470
 
                    print 'added', quotefn(f)
471
 
 
472
454
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
473
455
 
474
456
            self._write_inventory(inv)
584
566
            f.close()
585
567
 
586
568
 
587
 
    def get_revision_xml(self, revision_id):
 
569
    def get_revision_xml_file(self, revision_id):
588
570
        """Return XML file object for revision object."""
589
571
        if not revision_id or not isinstance(revision_id, basestring):
590
572
            raise InvalidRevisionId(revision_id)
594
576
            try:
595
577
                return self.revision_store[revision_id]
596
578
            except IndexError:
597
 
                raise bzrlib.errors.NoSuchRevision(revision_id)
 
579
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
598
580
        finally:
599
581
            self.unlock()
600
582
 
601
583
 
 
584
    #deprecated
 
585
    get_revision_xml = get_revision_xml_file
 
586
 
 
587
 
602
588
    def get_revision(self, revision_id):
603
589
        """Return the Revision object for a named revision"""
604
 
        xml_file = self.get_revision_xml(revision_id)
 
590
        xml_file = self.get_revision_xml_file(revision_id)
605
591
 
606
592
        try:
607
 
            r = unpack_xml(Revision, xml_file)
 
593
            r = bzrlib.xml.serializer_v4.read_revision(xml_file)
608
594
        except SyntaxError, e:
609
595
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
610
596
                                         [revision_id,
655
641
               parameter which can be either an integer revno or a
656
642
               string hash."""
657
643
        from bzrlib.inventory import Inventory
658
 
        from bzrlib.xml import unpack_xml
659
 
 
660
 
        return unpack_xml(Inventory, self.inventory_store[inventory_id])
 
644
 
 
645
        f = self.get_inventory_xml_file(inventory_id)
 
646
        return bzrlib.xml.serializer_v4.read_inventory(f)
 
647
 
 
648
 
 
649
    def get_inventory_xml(self, inventory_id):
 
650
        """Get inventory XML as a file object."""
 
651
        return self.inventory_store[inventory_id]
 
652
 
 
653
    get_inventory_xml_file = get_inventory_xml
661
654
            
662
655
 
663
656
    def get_inventory_sha1(self, inventory_id):
664
657
        """Return the sha1 hash of the inventory entry
665
658
        """
666
 
        return sha_file(self.inventory_store[inventory_id])
 
659
        return sha_file(self.get_inventory_xml(inventory_id))
667
660
 
668
661
 
669
662
    def get_revision_inventory(self, revision_id):
693
686
 
694
687
    def common_ancestor(self, other, self_revno=None, other_revno=None):
695
688
        """
696
 
        >>> import commit
 
689
        >>> from bzrlib.commit import commit
697
690
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
698
691
        >>> sb.common_ancestor(sb) == (None, None)
699
692
        True
700
 
        >>> commit.commit(sb, "Committing first revision", verbose=False)
 
693
        >>> commit(sb, "Committing first revision", verbose=False)
701
694
        >>> sb.common_ancestor(sb)[0]
702
695
        1
703
696
        >>> clone = sb.clone()
704
 
        >>> commit.commit(sb, "Committing second revision", verbose=False)
 
697
        >>> commit(sb, "Committing second revision", verbose=False)
705
698
        >>> sb.common_ancestor(sb)[0]
706
699
        2
707
700
        >>> sb.common_ancestor(clone)[0]
708
701
        1
709
 
        >>> commit.commit(clone, "Committing divergent second revision", 
 
702
        >>> commit(clone, "Committing divergent second revision", 
710
703
        ...               verbose=False)
711
704
        >>> sb.common_ancestor(clone)[0]
712
705
        1
755
748
            return None
756
749
 
757
750
 
758
 
    def missing_revisions(self, other, stop_revision=None):
 
751
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
759
752
        """
760
753
        If self and other have not diverged, return a list of the revisions
761
754
        present in other, but missing from self.
794
787
        if stop_revision is None:
795
788
            stop_revision = other_len
796
789
        elif stop_revision > other_len:
797
 
            raise NoSuchRevision(self, stop_revision)
 
790
            raise bzrlib.errors.NoSuchRevision(self, stop_revision)
798
791
        
799
792
        return other_history[self_len:stop_revision]
800
793
 
801
794
 
802
795
    def update_revisions(self, other, stop_revision=None):
803
796
        """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
797
        """
825
 
        from bzrlib.progress import ProgressBar
826
 
 
827
 
        pb = ProgressBar()
828
 
 
 
798
        from bzrlib.fetch import greedy_fetch
 
799
 
 
800
        pb = bzrlib.ui.ui_factory.progress_bar()
829
801
        pb.update('comparing histories')
 
802
 
830
803
        revision_ids = self.missing_revisions(other, stop_revision)
831
804
 
 
805
        if len(revision_ids) > 0:
 
806
            count = greedy_fetch(self, other, revision_ids[-1], pb)[0]
 
807
        else:
 
808
            count = 0
 
809
        self.append_revision(*revision_ids)
 
810
        ## note("Added %d revisions." % count)
 
811
        pb.clear()
 
812
 
 
813
    def install_revisions(self, other, revision_ids, pb):
832
814
        if hasattr(other.revision_store, "prefetch"):
833
815
            other.revision_store.prefetch(revision_ids)
834
816
        if hasattr(other.inventory_store, "prefetch"):
835
817
            inventory_ids = [other.get_revision(r).inventory_id
836
818
                             for r in revision_ids]
837
819
            other.inventory_store.prefetch(inventory_ids)
 
820
 
 
821
        if pb is None:
 
822
            pb = bzrlib.ui.ui_factory.progress_bar()
838
823
                
839
824
        revisions = []
840
825
        needed_texts = set()
841
826
        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)
 
827
 
 
828
        failures = set()
 
829
        for i, rev_id in enumerate(revision_ids):
 
830
            pb.update('fetching revision', i+1, len(revision_ids))
 
831
            try:
 
832
                rev = other.get_revision(rev_id)
 
833
            except bzrlib.errors.NoSuchRevision:
 
834
                failures.add(rev_id)
 
835
                continue
 
836
 
846
837
            revisions.append(rev)
847
838
            inv = other.get_inventory(str(rev.inventory_id))
848
839
            for key, entry in inv.iter_entries():
853
844
 
854
845
        pb.clear()
855
846
                    
856
 
        count = self.text_store.copy_multi(other.text_store, needed_texts)
857
 
        print "Added %d texts." % count 
 
847
        count, cp_fail = self.text_store.copy_multi(other.text_store, 
 
848
                                                    needed_texts)
 
849
        #print "Added %d texts." % count 
858
850
        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 
 
851
        count, cp_fail = self.inventory_store.copy_multi(other.inventory_store, 
 
852
                                                         inventory_ids)
 
853
        #print "Added %d inventories." % count 
862
854
        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
 
        
 
855
 
 
856
        count, cp_fail = self.revision_store.copy_multi(other.revision_store, 
 
857
                                                          revision_ids,
 
858
                                                          permit_failure=True)
 
859
        assert len(cp_fail) == 0 
 
860
        return count, failures
 
861
       
 
862
 
870
863
    def commit(self, *args, **kw):
871
864
        from bzrlib.commit import commit
872
865
        commit(self, *args, **kw)
874
867
 
875
868
    def lookup_revision(self, revision):
876
869
        """Return the revision identifier for a given revision information."""
877
 
        revno, info = self.get_revision_info(revision)
 
870
        revno, info = self._get_revision_info(revision)
878
871
        return info
879
872
 
 
873
 
 
874
    def revision_id_to_revno(self, revision_id):
 
875
        """Given a revision id, return its revno"""
 
876
        history = self.revision_history()
 
877
        try:
 
878
            return history.index(revision_id) + 1
 
879
        except ValueError:
 
880
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
881
 
 
882
 
880
883
    def get_revision_info(self, revision):
881
884
        """Return (revno, revision id) for revision identifier.
882
885
 
885
888
        revision can also be a string, in which case it is parsed for something like
886
889
            'date:' or 'revid:' etc.
887
890
        """
 
891
        revno, rev_id = self._get_revision_info(revision)
 
892
        if revno is None:
 
893
            raise bzrlib.errors.NoSuchRevision(self, revision)
 
894
        return revno, rev_id
 
895
 
 
896
    def get_rev_id(self, revno, history=None):
 
897
        """Find the revision id of the specified revno."""
 
898
        if revno == 0:
 
899
            return None
 
900
        if history is None:
 
901
            history = self.revision_history()
 
902
        elif revno <= 0 or revno > len(history):
 
903
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
904
        return history[revno - 1]
 
905
 
 
906
    def _get_revision_info(self, revision):
 
907
        """Return (revno, revision id) for revision specifier.
 
908
 
 
909
        revision can be an integer, in which case it is assumed to be revno
 
910
        (though this will translate negative values into positive ones)
 
911
        revision can also be a string, in which case it is parsed for something
 
912
        like 'date:' or 'revid:' etc.
 
913
 
 
914
        A revid is always returned.  If it is None, the specifier referred to
 
915
        the null revision.  If the revid does not occur in the revision
 
916
        history, revno will be None.
 
917
        """
 
918
        
888
919
        if revision is None:
889
920
            return 0, None
890
921
        revno = None
894
925
            pass
895
926
        revs = self.revision_history()
896
927
        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
928
            if revision < 0:
901
929
                revno = len(revs) + revision + 1
902
930
            else:
903
931
                revno = revision
 
932
            rev_id = self.get_rev_id(revno, revs)
904
933
        elif isinstance(revision, basestring):
905
934
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
906
935
                if revision.startswith(prefix):
907
 
                    revno = func(self, revs, revision)
 
936
                    result = func(self, revs, revision)
 
937
                    if len(result) > 1:
 
938
                        revno, rev_id = result
 
939
                    else:
 
940
                        revno = result[0]
 
941
                        rev_id = self.get_rev_id(revno, revs)
908
942
                    break
909
943
            else:
910
 
                raise BzrError('No namespace registered for string: %r' % revision)
 
944
                raise BzrError('No namespace registered for string: %r' %
 
945
                               revision)
 
946
        else:
 
947
            raise TypeError('Unhandled revision type %s' % revision)
911
948
 
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]
 
949
        if revno is None:
 
950
            if rev_id is None:
 
951
                raise bzrlib.errors.NoSuchRevision(self, revision)
 
952
        return revno, rev_id
915
953
 
916
954
    def _namespace_revno(self, revs, revision):
917
955
        """Lookup a revision by revision number"""
918
956
        assert revision.startswith('revno:')
919
957
        try:
920
 
            return int(revision[6:])
 
958
            return (int(revision[6:]),)
921
959
        except ValueError:
922
960
            return None
923
961
    REVISION_NAMESPACES['revno:'] = _namespace_revno
924
962
 
925
963
    def _namespace_revid(self, revs, revision):
926
964
        assert revision.startswith('revid:')
 
965
        rev_id = revision[len('revid:'):]
927
966
        try:
928
 
            return revs.index(revision[6:]) + 1
 
967
            return revs.index(rev_id) + 1, rev_id
929
968
        except ValueError:
930
 
            return None
 
969
            return None, rev_id
931
970
    REVISION_NAMESPACES['revid:'] = _namespace_revid
932
971
 
933
972
    def _namespace_last(self, revs, revision):
935
974
        try:
936
975
            offset = int(revision[5:])
937
976
        except ValueError:
938
 
            return None
 
977
            return (None,)
939
978
        else:
940
979
            if offset <= 0:
941
980
                raise BzrError('You must supply a positive value for --revision last:XXX')
942
 
            return len(revs) - offset + 1
 
981
            return (len(revs) - offset + 1,)
943
982
    REVISION_NAMESPACES['last:'] = _namespace_last
944
983
 
945
984
    def _namespace_tag(self, revs, revision):
1020
1059
                # TODO: Handle timezone.
1021
1060
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1022
1061
                if first >= dt and (last is None or dt >= last):
1023
 
                    return i+1
 
1062
                    return (i+1,)
1024
1063
        else:
1025
1064
            for i in range(len(revs)):
1026
1065
                r = self.get_revision(revs[i])
1027
1066
                # TODO: Handle timezone.
1028
1067
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1029
1068
                if first <= dt and (last is None or dt <= last):
1030
 
                    return i+1
 
1069
                    return (i+1,)
1031
1070
    REVISION_NAMESPACES['date:'] = _namespace_date
1032
1071
 
1033
1072
    def revision_tree(self, revision_id):
1046
1085
 
1047
1086
    def working_tree(self):
1048
1087
        """Return a `Tree` for the working copy."""
1049
 
        from workingtree import WorkingTree
 
1088
        from bzrlib.workingtree import WorkingTree
1050
1089
        return WorkingTree(self.base, self.read_working_inventory())
1051
1090
 
1052
1091
 
1098
1137
 
1099
1138
            inv.rename(file_id, to_dir_id, to_tail)
1100
1139
 
1101
 
            print "%s => %s" % (from_rel, to_rel)
1102
 
 
1103
1140
            from_abs = self.abspath(from_rel)
1104
1141
            to_abs = self.abspath(to_rel)
1105
1142
            try:
1124
1161
 
1125
1162
        Note that to_name is only the last component of the new name;
1126
1163
        this doesn't change the directory.
 
1164
 
 
1165
        This returns a list of (from_path, to_path) pairs for each
 
1166
        entry that is moved.
1127
1167
        """
 
1168
        result = []
1128
1169
        self.lock_write()
1129
1170
        try:
1130
1171
            ## TODO: Option to move IDs only
1165
1206
            for f in from_paths:
1166
1207
                name_tail = splitpath(f)[-1]
1167
1208
                dest_path = appendpath(to_name, name_tail)
1168
 
                print "%s => %s" % (f, dest_path)
 
1209
                result.append((f, dest_path))
1169
1210
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1170
1211
                try:
1171
1212
                    os.rename(self.abspath(f), self.abspath(dest_path))
1177
1218
        finally:
1178
1219
            self.unlock()
1179
1220
 
 
1221
        return result
 
1222
 
1180
1223
 
1181
1224
    def revert(self, filenames, old_tree=None, backups=True):
1182
1225
        """Restore selected files to the versions from a previous tree.
1264
1307
            self.unlock()
1265
1308
 
1266
1309
 
 
1310
    def get_parent(self):
 
1311
        """Return the parent location of the branch.
 
1312
 
 
1313
        This is the default location for push/pull/missing.  The usual
 
1314
        pattern is that the user can override it by specifying a
 
1315
        location.
 
1316
        """
 
1317
        import errno
 
1318
        _locs = ['parent', 'pull', 'x-pull']
 
1319
        for l in _locs:
 
1320
            try:
 
1321
                return self.controlfile(l, 'r').read().strip('\n')
 
1322
            except IOError, e:
 
1323
                if e.errno != errno.ENOENT:
 
1324
                    raise
 
1325
        return None
 
1326
 
 
1327
 
 
1328
    def set_parent(self, url):
 
1329
        # TODO: Maybe delete old location files?
 
1330
        from bzrlib.atomicfile import AtomicFile
 
1331
        self.lock_write()
 
1332
        try:
 
1333
            f = AtomicFile(self.controlfilename('parent'))
 
1334
            try:
 
1335
                f.write(url + '\n')
 
1336
                f.commit()
 
1337
            finally:
 
1338
                f.close()
 
1339
        finally:
 
1340
            self.unlock()
 
1341
 
 
1342
    def check_revno(self, revno):
 
1343
        """\
 
1344
        Check whether a revno corresponds to any revision.
 
1345
        Zero (the NULL revision) is considered valid.
 
1346
        """
 
1347
        if revno != 0:
 
1348
            self.check_real_revno(revno)
 
1349
            
 
1350
    def check_real_revno(self, revno):
 
1351
        """\
 
1352
        Check whether a revno corresponds to a real revision.
 
1353
        Zero (the NULL revision) is considered invalid
 
1354
        """
 
1355
        if revno < 1 or revno > self.revno():
 
1356
            raise InvalidRevisionNumber(revno)
 
1357
        
 
1358
        
 
1359
 
1267
1360
 
1268
1361
class ScratchBranch(Branch):
1269
1362
    """Special test class: a branch that cleans up after itself.
1311
1404
        os.rmdir(base)
1312
1405
        copytree(self.base, base, symlinks=True)
1313
1406
        return ScratchBranch(base=base)
 
1407
 
 
1408
 
1314
1409
        
1315
1410
    def __del__(self):
1316
1411
        self.destroy()
1386
1481
    """Return a new tree-root file id."""
1387
1482
    return gen_file_id('TREE_ROOT')
1388
1483
 
 
1484
 
 
1485
def copy_branch(branch_from, to_location, revision=None):
 
1486
    """Copy branch_from into the existing directory to_location.
 
1487
 
 
1488
    revision
 
1489
        If not None, only revisions up to this point will be copied.
 
1490
        The head of the new branch will be that revision.
 
1491
 
 
1492
    to_location
 
1493
        The name of a local directory that exists but is empty.
 
1494
    """
 
1495
    from bzrlib.merge import merge
 
1496
 
 
1497
    assert isinstance(branch_from, Branch)
 
1498
    assert isinstance(to_location, basestring)
 
1499
    
 
1500
    br_to = Branch(to_location, init=True)
 
1501
    br_to.set_root_id(branch_from.get_root_id())
 
1502
    if revision is None:
 
1503
        revno = branch_from.revno()
 
1504
    else:
 
1505
        revno, rev_id = branch_from.get_revision_info(revision)
 
1506
    br_to.update_revisions(branch_from, stop_revision=revno)
 
1507
    merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
1508
          check_clean=False, ignore_zero=True)
 
1509
    
 
1510
    from_location = branch_from.base
 
1511
    br_to.set_parent(branch_from.base)
 
1512