~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: aaron.bentley at utoronto
  • Date: 2005-08-25 02:10:04 UTC
  • mto: (1092.1.41) (1185.3.4)
  • mto: This revision was merged to the branch mainline in revision 1139.
  • Revision ID: aaron.bentley@utoronto.ca-20050825021004-a7afd22f3dd52b2e
pending merges, common ancestor work properly

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
 
 
27
 
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId, \
28
 
     DivergedBranches, NotBranchError
 
26
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId
 
27
import bzrlib.errors
29
28
from bzrlib.textui import show_status
30
29
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
 
import bzrlib.xml
34
 
import bzrlib.ui
35
 
 
36
 
 
37
 
 
 
33
from bzrlib.progress import ProgressBar
 
34
 
 
35
       
38
36
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
39
37
## TODO: Maybe include checks for common corruption of newlines, etc?
40
38
 
49
47
 
50
48
def find_branch(f, **args):
51
49
    if f and (f.startswith('http://') or f.startswith('https://')):
52
 
        from bzrlib.remotebranch import RemoteBranch
53
 
        return RemoteBranch(f, **args)
 
50
        import remotebranch 
 
51
        return remotebranch.RemoteBranch(f, **args)
54
52
    else:
55
53
        return Branch(f, **args)
56
54
 
57
55
 
58
56
def find_cached_branch(f, cache_root, **args):
59
 
    from bzrlib.remotebranch import RemoteBranch
 
57
    from remotebranch import RemoteBranch
60
58
    br = find_branch(f, **args)
61
59
    def cacheify(br, store_name):
62
 
        from bzrlib.meta_store import CachedStore
 
60
        from meta_store import CachedStore
63
61
        cache_path = os.path.join(cache_root, store_name)
64
62
        os.mkdir(cache_path)
65
63
        new_store = CachedStore(getattr(br, store_name), cache_path)
94
92
        if tail:
95
93
            s.insert(0, tail)
96
94
    else:
 
95
        from errors import NotBranchError
97
96
        raise NotBranchError("path %r is not within branch %r" % (rp, base))
98
97
 
99
98
    return os.sep.join(s)
107
106
    It is not necessary that f exists.
108
107
 
109
108
    Basically we keep looking up until we find the control directory or
110
 
    run into the root.  If there isn't one, raises NotBranchError.
111
 
    """
 
109
    run into the root."""
112
110
    if f == None:
113
111
        f = os.getcwd()
114
112
    elif hasattr(os.path, 'realpath'):
127
125
        head, tail = os.path.split(f)
128
126
        if head == f:
129
127
            # reached the root, whatever that may be
130
 
            raise NotBranchError('%s is not in a branch' % orig_f)
 
128
            raise BzrError('%r is not in a branch' % orig_f)
131
129
        f = head
132
 
 
133
 
 
 
130
    
 
131
class DivergedBranches(Exception):
 
132
    def __init__(self, branch1, branch2):
 
133
        self.branch1 = branch1
 
134
        self.branch2 = branch2
 
135
        Exception.__init__(self, "These branches have diverged.")
134
136
 
135
137
 
136
138
######################################################################
165
167
    def __init__(self, base, init=False, find_root=True):
166
168
        """Create new branch object at a particular location.
167
169
 
168
 
        base -- Base directory for the branch. May be a file:// url.
 
170
        base -- Base directory for the branch.
169
171
        
170
172
        init -- If True, create new control files in a previously
171
173
             unversioned directory.  If False, the branch must already
184
186
        elif find_root:
185
187
            self.base = find_branch_root(base)
186
188
        else:
187
 
            if base.startswith("file://"):
188
 
                base = base[7:]
189
189
            self.base = os.path.realpath(base)
190
190
            if not isdir(self.controlfilename('.')):
 
191
                from errors import NotBranchError
191
192
                raise NotBranchError("not a bzr branch: %s" % quotefn(base),
192
193
                                     ['use "bzr init" to initialize a new working tree',
193
194
                                      'current bzr can only operate from top-of-tree'])
207
208
 
208
209
    def __del__(self):
209
210
        if self._lock_mode or self._lock:
210
 
            from bzrlib.warnings import warn
 
211
            from warnings import warn
211
212
            warn("branch %r was not explicitly unlocked" % self)
212
213
            self._lock.unlock()
213
214
 
 
215
 
 
216
 
214
217
    def lock_write(self):
215
218
        if self._lock_mode:
216
219
            if self._lock_mode != 'w':
217
 
                from bzrlib.errors import LockError
 
220
                from errors import LockError
218
221
                raise LockError("can't upgrade to a write lock from %r" %
219
222
                                self._lock_mode)
220
223
            self._lock_count += 1
226
229
            self._lock_count = 1
227
230
 
228
231
 
 
232
 
229
233
    def lock_read(self):
230
234
        if self._lock_mode:
231
235
            assert self._lock_mode in ('r', 'w'), \
238
242
            self._lock_mode = 'r'
239
243
            self._lock_count = 1
240
244
                        
 
245
 
 
246
            
241
247
    def unlock(self):
242
248
        if not self._lock_mode:
243
 
            from bzrlib.errors import LockError
 
249
            from errors import LockError
244
250
            raise LockError('branch %r is not locked' % (self))
245
251
 
246
252
        if self._lock_count > 1:
250
256
            self._lock = None
251
257
            self._lock_mode = self._lock_count = None
252
258
 
 
259
 
253
260
    def abspath(self, name):
254
261
        """Return absolute filename for something in the branch"""
255
262
        return os.path.join(self.base, name)
256
263
 
 
264
 
257
265
    def relpath(self, path):
258
266
        """Return path relative to this branch of something inside it.
259
267
 
260
268
        Raises an error if path is not in this branch."""
261
269
        return _relpath(self.base, path)
262
270
 
 
271
 
263
272
    def controlfilename(self, file_or_path):
264
273
        """Return location relative to branch."""
265
274
        if isinstance(file_or_path, basestring):
292
301
        else:
293
302
            raise BzrError("invalid controlfile mode %r" % mode)
294
303
 
 
304
 
 
305
 
295
306
    def _make_control(self):
296
307
        from bzrlib.inventory import Inventory
 
308
        from bzrlib.xml import pack_xml
297
309
        
298
310
        os.mkdir(self.controlfilename([]))
299
311
        self.controlfile('README', 'w').write(
312
324
        # if we want per-tree root ids then this is the place to set
313
325
        # them; they're not needed for now and so ommitted for
314
326
        # simplicity.
315
 
        f = self.controlfile('inventory','w')
316
 
        bzrlib.xml.serializer_v4.write_inventory(Inventory(), f)
 
327
        pack_xml(Inventory(), self.controlfile('inventory','w'))
317
328
 
318
329
 
319
330
    def _check_format(self):
328
339
        # on Windows from Linux and so on.  I think it might be better
329
340
        # to always make all internal files in unix format.
330
341
        fmt = self.controlfile('branch-format', 'r').read()
331
 
        fmt = fmt.replace('\r\n', '\n')
 
342
        fmt.replace('\r\n', '')
332
343
        if fmt != BZR_BRANCH_FORMAT:
333
344
            raise BzrError('sorry, branch format %r not supported' % fmt,
334
345
                           ['use a different bzr version',
354
365
    def read_working_inventory(self):
355
366
        """Read the working inventory."""
356
367
        from bzrlib.inventory import Inventory
 
368
        from bzrlib.xml import unpack_xml
 
369
        from time import time
 
370
        before = time()
357
371
        self.lock_read()
358
372
        try:
359
373
            # ElementTree does its own conversion from UTF-8, so open in
360
374
            # binary.
361
 
            f = self.controlfile('inventory', 'rb')
362
 
            return bzrlib.xml.serializer_v4.read_inventory(f)
 
375
            inv = unpack_xml(Inventory,
 
376
                             self.controlfile('inventory', 'rb'))
 
377
            mutter("loaded inventory of %d items in %f"
 
378
                   % (len(inv), time() - before))
 
379
            return inv
363
380
        finally:
364
381
            self.unlock()
365
382
            
371
388
        will be committed to the next revision.
372
389
        """
373
390
        from bzrlib.atomicfile import AtomicFile
 
391
        from bzrlib.xml import pack_xml
374
392
        
375
393
        self.lock_write()
376
394
        try:
377
395
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
378
396
            try:
379
 
                bzrlib.xml.serializer_v4.write_inventory(inv, f)
 
397
                pack_xml(inv, f)
380
398
                f.commit()
381
399
            finally:
382
400
                f.close()
390
408
                         """Inventory for the working copy.""")
391
409
 
392
410
 
393
 
    def add(self, files, ids=None):
 
411
    def add(self, files, verbose=False, ids=None):
394
412
        """Make files versioned.
395
413
 
396
 
        Note that the command line normally calls smart_add instead,
397
 
        which can automatically recurse.
 
414
        Note that the command line normally calls smart_add instead.
398
415
 
399
416
        This puts the files in the Added state, so that they will be
400
417
        recorded by the next commit.
410
427
        TODO: Perhaps have an option to add the ids even if the files do
411
428
              not (yet) exist.
412
429
 
413
 
        TODO: Perhaps yield the ids and paths as they're added.
 
430
        TODO: Perhaps return the ids of the files?  But then again it
 
431
              is easy to retrieve them if they're needed.
 
432
 
 
433
        TODO: Adding a directory should optionally recurse down and
 
434
              add all non-ignored children.  Perhaps do that in a
 
435
              higher-level method.
414
436
        """
415
437
        # TODO: Re-adding a file that is removed in the working copy
416
438
        # should probably put it back with the previous ID.
452
474
                    file_id = gen_file_id(f)
453
475
                inv.add_path(f, kind=kind, file_id=file_id)
454
476
 
 
477
                if verbose:
 
478
                    print 'added', quotefn(f)
 
479
 
455
480
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
456
481
 
457
482
            self._write_inventory(inv)
567
592
            f.close()
568
593
 
569
594
 
570
 
    def get_revision_xml_file(self, revision_id):
 
595
    def get_revision_xml(self, revision_id):
571
596
        """Return XML file object for revision object."""
572
597
        if not revision_id or not isinstance(revision_id, basestring):
573
598
            raise InvalidRevisionId(revision_id)
576
601
        try:
577
602
            try:
578
603
                return self.revision_store[revision_id]
579
 
            except KeyError:
 
604
            except IndexError:
580
605
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
581
606
        finally:
582
607
            self.unlock()
583
608
 
584
609
 
585
 
    #deprecated
586
 
    get_revision_xml = get_revision_xml_file
587
 
 
588
 
 
589
610
    def get_revision(self, revision_id):
590
611
        """Return the Revision object for a named revision"""
591
 
        xml_file = self.get_revision_xml_file(revision_id)
 
612
        xml_file = self.get_revision_xml(revision_id)
592
613
 
593
614
        try:
594
 
            r = bzrlib.xml.serializer_v4.read_revision(xml_file)
 
615
            r = unpack_xml(Revision, xml_file)
595
616
        except SyntaxError, e:
596
617
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
597
618
                                         [revision_id,
642
663
               parameter which can be either an integer revno or a
643
664
               string hash."""
644
665
        from bzrlib.inventory import Inventory
 
666
        from bzrlib.xml import unpack_xml
645
667
 
646
 
        f = self.get_inventory_xml_file(inventory_id)
647
 
        return bzrlib.xml.serializer_v4.read_inventory(f)
 
668
        return unpack_xml(Inventory, self.get_inventory_xml(inventory_id))
648
669
 
649
670
 
650
671
    def get_inventory_xml(self, inventory_id):
651
672
        """Get inventory XML as a file object."""
652
673
        return self.inventory_store[inventory_id]
653
 
 
654
 
    get_inventory_xml_file = get_inventory_xml
655
674
            
656
675
 
657
676
    def get_inventory_sha1(self, inventory_id):
687
706
 
688
707
    def common_ancestor(self, other, self_revno=None, other_revno=None):
689
708
        """
690
 
        >>> from bzrlib.commit import commit
 
709
        >>> import commit
691
710
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
692
711
        >>> sb.common_ancestor(sb) == (None, None)
693
712
        True
694
 
        >>> commit(sb, "Committing first revision", verbose=False)
 
713
        >>> commit.commit(sb, "Committing first revision", verbose=False)
695
714
        >>> sb.common_ancestor(sb)[0]
696
715
        1
697
716
        >>> clone = sb.clone()
698
 
        >>> commit(sb, "Committing second revision", verbose=False)
 
717
        >>> commit.commit(sb, "Committing second revision", verbose=False)
699
718
        >>> sb.common_ancestor(sb)[0]
700
719
        2
701
720
        >>> sb.common_ancestor(clone)[0]
702
721
        1
703
 
        >>> commit(clone, "Committing divergent second revision", 
 
722
        >>> commit.commit(clone, "Committing divergent second revision", 
704
723
        ...               verbose=False)
705
724
        >>> sb.common_ancestor(clone)[0]
706
725
        1
788
807
        if stop_revision is None:
789
808
            stop_revision = other_len
790
809
        elif stop_revision > other_len:
791
 
            raise bzrlib.errors.NoSuchRevision(self, stop_revision)
 
810
            raise NoSuchRevision(self, stop_revision)
792
811
        
793
812
        return other_history[self_len:stop_revision]
794
813
 
795
814
 
796
815
    def update_revisions(self, other, stop_revision=None):
797
816
        """Pull in all new revisions from other branch.
 
817
        
 
818
        >>> from bzrlib.commit import commit
 
819
        >>> bzrlib.trace.silent = True
 
820
        >>> br1 = ScratchBranch(files=['foo', 'bar'])
 
821
        >>> br1.add('foo')
 
822
        >>> br1.add('bar')
 
823
        >>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
 
824
        >>> br2 = ScratchBranch()
 
825
        >>> br2.update_revisions(br1)
 
826
        Added 2 texts.
 
827
        Added 1 inventories.
 
828
        Added 1 revisions.
 
829
        >>> br2.revision_history()
 
830
        [u'REVISION-ID-1']
 
831
        >>> br2.update_revisions(br1)
 
832
        Added 0 revisions.
 
833
        >>> br1.text_store.total_size() == br2.text_store.total_size()
 
834
        True
798
835
        """
799
836
        from bzrlib.fetch import greedy_fetch
800
 
        from bzrlib.revision import get_intervening_revisions
801
 
 
802
 
        pb = bzrlib.ui.ui_factory.progress_bar()
 
837
        pb = ProgressBar()
803
838
        pb.update('comparing histories')
804
 
        if stop_revision is None:
805
 
            other_revision = other.last_patch()
 
839
        revision_ids = self.missing_revisions(other, stop_revision)
 
840
        if len(revision_ids) > 0:
 
841
            count = greedy_fetch(self, other, revision_ids[-1], pb)[0]
806
842
        else:
807
 
            other_revision = other.lookup_revision(stop_revision)
808
 
        count = greedy_fetch(self, other, other_revision, pb)[0]
809
 
        try:
810
 
            revision_ids = self.missing_revisions(other, stop_revision)
811
 
        except DivergedBranches, e:
812
 
            try:
813
 
                revision_ids = get_intervening_revisions(self.last_patch(), 
814
 
                                                         other_revision, self)
815
 
                assert self.last_patch() not in revision_ids
816
 
            except bzrlib.errors.NotAncestor:
817
 
                raise e
818
 
 
 
843
            count = 0
819
844
        self.append_revision(*revision_ids)
820
 
        pb.clear()
821
 
 
822
 
    def install_revisions(self, other, revision_ids, pb):
 
845
        print "Added %d revisions." % count
 
846
                    
 
847
    def install_revisions(self, other, revision_ids, pb=None):
 
848
        if pb is None:
 
849
            pb = ProgressBar()
823
850
        if hasattr(other.revision_store, "prefetch"):
824
851
            other.revision_store.prefetch(revision_ids)
825
852
        if hasattr(other.inventory_store, "prefetch"):
826
 
            inventory_ids = []
827
 
            for rev_id in revision_ids:
828
 
                try:
829
 
                    revision = other.get_revision(rev_id).inventory_id
830
 
                    inventory_ids.append(revision)
831
 
                except bzrlib.errors.NoSuchRevision:
832
 
                    pass
 
853
            inventory_ids = [other.get_revision(r).inventory_id
 
854
                             for r in revision_ids]
833
855
            other.inventory_store.prefetch(inventory_ids)
834
 
 
835
 
        if pb is None:
836
 
            pb = bzrlib.ui.ui_factory.progress_bar()
837
856
                
838
857
        revisions = []
839
858
        needed_texts = set()
840
859
        i = 0
841
 
 
842
860
        failures = set()
843
861
        for i, rev_id in enumerate(revision_ids):
844
862
            pb.update('fetching revision', i+1, len(revision_ids))
847
865
            except bzrlib.errors.NoSuchRevision:
848
866
                failures.add(rev_id)
849
867
                continue
850
 
 
851
868
            revisions.append(rev)
852
869
            inv = other.get_inventory(str(rev.inventory_id))
853
870
            for key, entry in inv.iter_entries():
860
877
                    
861
878
        count, cp_fail = self.text_store.copy_multi(other.text_store, 
862
879
                                                    needed_texts)
863
 
        #print "Added %d texts." % count 
 
880
        print "Added %d texts." % count 
864
881
        inventory_ids = [ f.inventory_id for f in revisions ]
865
882
        count, cp_fail = self.inventory_store.copy_multi(other.inventory_store, 
866
883
                                                         inventory_ids)
867
 
        #print "Added %d inventories." % count 
 
884
        print "Added %d inventories." % count 
868
885
        revision_ids = [ f.revision_id for f in revisions]
869
 
 
870
886
        count, cp_fail = self.revision_store.copy_multi(other.revision_store, 
871
887
                                                          revision_ids,
872
888
                                                          permit_failure=True)
873
889
        assert len(cp_fail) == 0 
874
890
        return count, failures
875
891
       
876
 
 
877
892
    def commit(self, *args, **kw):
878
893
        from bzrlib.commit import commit
879
894
        commit(self, *args, **kw)
881
896
 
882
897
    def lookup_revision(self, revision):
883
898
        """Return the revision identifier for a given revision information."""
884
 
        revno, info = self._get_revision_info(revision)
 
899
        revno, info = self.get_revision_info(revision)
885
900
        return info
886
901
 
887
 
 
888
 
    def revision_id_to_revno(self, revision_id):
889
 
        """Given a revision id, return its revno"""
890
 
        history = self.revision_history()
891
 
        try:
892
 
            return history.index(revision_id) + 1
893
 
        except ValueError:
894
 
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
895
 
 
896
 
 
897
902
    def get_revision_info(self, revision):
898
903
        """Return (revno, revision id) for revision identifier.
899
904
 
902
907
        revision can also be a string, in which case it is parsed for something like
903
908
            'date:' or 'revid:' etc.
904
909
        """
905
 
        revno, rev_id = self._get_revision_info(revision)
906
 
        if revno is None:
907
 
            raise bzrlib.errors.NoSuchRevision(self, revision)
908
 
        return revno, rev_id
909
 
 
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
 
 
920
 
    def _get_revision_info(self, revision):
921
 
        """Return (revno, revision id) for revision specifier.
922
 
 
923
 
        revision can be an integer, in which case it is assumed to be revno
924
 
        (though this will translate negative values into positive ones)
925
 
        revision can also be a string, in which case it is parsed for something
926
 
        like 'date:' or 'revid:' etc.
927
 
 
928
 
        A revid is always returned.  If it is None, the specifier referred to
929
 
        the null revision.  If the revid does not occur in the revision
930
 
        history, revno will be None.
931
 
        """
932
 
        
933
910
        if revision is None:
934
911
            return 0, None
935
912
        revno = None
939
916
            pass
940
917
        revs = self.revision_history()
941
918
        if isinstance(revision, int):
 
919
            if revision == 0:
 
920
                return 0, None
 
921
            # Mabye we should do this first, but we don't need it if revision == 0
942
922
            if revision < 0:
943
923
                revno = len(revs) + revision + 1
944
924
            else:
945
925
                revno = revision
946
 
            rev_id = self.get_rev_id(revno, revs)
947
926
        elif isinstance(revision, basestring):
948
927
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
949
928
                if revision.startswith(prefix):
950
 
                    result = func(self, revs, revision)
951
 
                    if len(result) > 1:
952
 
                        revno, rev_id = result
953
 
                    else:
954
 
                        revno = result[0]
955
 
                        rev_id = self.get_rev_id(revno, revs)
 
929
                    revno = func(self, revs, revision)
956
930
                    break
957
931
            else:
958
 
                raise BzrError('No namespace registered for string: %r' %
959
 
                               revision)
960
 
        else:
961
 
            raise TypeError('Unhandled revision type %s' % revision)
 
932
                raise BzrError('No namespace registered for string: %r' % revision)
962
933
 
963
 
        if revno is None:
964
 
            if rev_id is None:
965
 
                raise bzrlib.errors.NoSuchRevision(self, revision)
966
 
        return revno, rev_id
 
934
        if revno is None or revno <= 0 or revno > len(revs):
 
935
            raise BzrError("no such revision %s" % revision)
 
936
        return revno, revs[revno-1]
967
937
 
968
938
    def _namespace_revno(self, revs, revision):
969
939
        """Lookup a revision by revision number"""
970
940
        assert revision.startswith('revno:')
971
941
        try:
972
 
            return (int(revision[6:]),)
 
942
            return int(revision[6:])
973
943
        except ValueError:
974
944
            return None
975
945
    REVISION_NAMESPACES['revno:'] = _namespace_revno
976
946
 
977
947
    def _namespace_revid(self, revs, revision):
978
948
        assert revision.startswith('revid:')
979
 
        rev_id = revision[len('revid:'):]
980
949
        try:
981
 
            return revs.index(rev_id) + 1, rev_id
 
950
            return revs.index(revision[6:]) + 1
982
951
        except ValueError:
983
 
            return None, rev_id
 
952
            return None
984
953
    REVISION_NAMESPACES['revid:'] = _namespace_revid
985
954
 
986
955
    def _namespace_last(self, revs, revision):
988
957
        try:
989
958
            offset = int(revision[5:])
990
959
        except ValueError:
991
 
            return (None,)
 
960
            return None
992
961
        else:
993
962
            if offset <= 0:
994
963
                raise BzrError('You must supply a positive value for --revision last:XXX')
995
 
            return (len(revs) - offset + 1,)
 
964
            return len(revs) - offset + 1
996
965
    REVISION_NAMESPACES['last:'] = _namespace_last
997
966
 
998
967
    def _namespace_tag(self, revs, revision):
1073
1042
                # TODO: Handle timezone.
1074
1043
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1075
1044
                if first >= dt and (last is None or dt >= last):
1076
 
                    return (i+1,)
 
1045
                    return i+1
1077
1046
        else:
1078
1047
            for i in range(len(revs)):
1079
1048
                r = self.get_revision(revs[i])
1080
1049
                # TODO: Handle timezone.
1081
1050
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1082
1051
                if first <= dt and (last is None or dt <= last):
1083
 
                    return (i+1,)
 
1052
                    return i+1
1084
1053
    REVISION_NAMESPACES['date:'] = _namespace_date
1085
1054
 
1086
 
 
1087
 
    def _namespace_ancestor(self, revs, revision):
1088
 
        from revision import common_ancestor, MultipleRevisionSources
1089
 
        other_branch = find_branch(_trim_namespace('ancestor', revision))
1090
 
        revision_a = self.last_patch()
1091
 
        revision_b = other_branch.last_patch()
1092
 
        for r, b in ((revision_a, self), (revision_b, other_branch)):
1093
 
            if r is None:
1094
 
                raise bzrlib.errors.NoCommits(b)
1095
 
        revision_source = MultipleRevisionSources(self, other_branch)
1096
 
        result = common_ancestor(revision_a, revision_b, revision_source)
1097
 
        try:
1098
 
            revno = self.revision_id_to_revno(result)
1099
 
        except bzrlib.errors.NoSuchRevision:
1100
 
            revno = None
1101
 
        return revno,result
1102
 
        
1103
 
 
1104
 
    REVISION_NAMESPACES['ancestor:'] = _namespace_ancestor
1105
 
 
1106
1055
    def revision_tree(self, revision_id):
1107
1056
        """Return Tree for a revision on this branch.
1108
1057
 
1119
1068
 
1120
1069
    def working_tree(self):
1121
1070
        """Return a `Tree` for the working copy."""
1122
 
        from bzrlib.workingtree import WorkingTree
 
1071
        from workingtree import WorkingTree
1123
1072
        return WorkingTree(self.base, self.read_working_inventory())
1124
1073
 
1125
1074
 
1171
1120
 
1172
1121
            inv.rename(file_id, to_dir_id, to_tail)
1173
1122
 
 
1123
            print "%s => %s" % (from_rel, to_rel)
 
1124
 
1174
1125
            from_abs = self.abspath(from_rel)
1175
1126
            to_abs = self.abspath(to_rel)
1176
1127
            try:
1195
1146
 
1196
1147
        Note that to_name is only the last component of the new name;
1197
1148
        this doesn't change the directory.
1198
 
 
1199
 
        This returns a list of (from_path, to_path) pairs for each
1200
 
        entry that is moved.
1201
1149
        """
1202
 
        result = []
1203
1150
        self.lock_write()
1204
1151
        try:
1205
1152
            ## TODO: Option to move IDs only
1240
1187
            for f in from_paths:
1241
1188
                name_tail = splitpath(f)[-1]
1242
1189
                dest_path = appendpath(to_name, name_tail)
1243
 
                result.append((f, dest_path))
 
1190
                print "%s => %s" % (f, dest_path)
1244
1191
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1245
1192
                try:
1246
1193
                    os.rename(self.abspath(f), self.abspath(dest_path))
1252
1199
        finally:
1253
1200
            self.unlock()
1254
1201
 
1255
 
        return result
1256
 
 
1257
1202
 
1258
1203
    def revert(self, filenames, old_tree=None, backups=True):
1259
1204
        """Restore selected files to the versions from a previous tree.
1341
1286
            self.unlock()
1342
1287
 
1343
1288
 
1344
 
    def get_parent(self):
1345
 
        """Return the parent location of the branch.
1346
 
 
1347
 
        This is the default location for push/pull/missing.  The usual
1348
 
        pattern is that the user can override it by specifying a
1349
 
        location.
1350
 
        """
1351
 
        import errno
1352
 
        _locs = ['parent', 'pull', 'x-pull']
1353
 
        for l in _locs:
1354
 
            try:
1355
 
                return self.controlfile(l, 'r').read().strip('\n')
1356
 
            except IOError, e:
1357
 
                if e.errno != errno.ENOENT:
1358
 
                    raise
1359
 
        return None
1360
 
 
1361
 
 
1362
 
    def set_parent(self, url):
1363
 
        # TODO: Maybe delete old location files?
1364
 
        from bzrlib.atomicfile import AtomicFile
1365
 
        self.lock_write()
1366
 
        try:
1367
 
            f = AtomicFile(self.controlfilename('parent'))
1368
 
            try:
1369
 
                f.write(url + '\n')
1370
 
                f.commit()
1371
 
            finally:
1372
 
                f.close()
1373
 
        finally:
1374
 
            self.unlock()
1375
 
 
1376
 
    def check_revno(self, revno):
1377
 
        """\
1378
 
        Check whether a revno corresponds to any revision.
1379
 
        Zero (the NULL revision) is considered valid.
1380
 
        """
1381
 
        if revno != 0:
1382
 
            self.check_real_revno(revno)
1383
 
            
1384
 
    def check_real_revno(self, revno):
1385
 
        """\
1386
 
        Check whether a revno corresponds to a real revision.
1387
 
        Zero (the NULL revision) is considered invalid
1388
 
        """
1389
 
        if revno < 1 or revno > self.revno():
1390
 
            raise InvalidRevisionNumber(revno)
1391
 
        
1392
 
        
1393
 
 
1394
1289
 
1395
1290
class ScratchBranch(Branch):
1396
1291
    """Special test class: a branch that cleans up after itself.
1438
1333
        os.rmdir(base)
1439
1334
        copytree(self.base, base, symlinks=True)
1440
1335
        return ScratchBranch(base=base)
1441
 
 
1442
 
 
1443
1336
        
1444
1337
    def __del__(self):
1445
1338
        self.destroy()
1515
1408
    """Return a new tree-root file id."""
1516
1409
    return gen_file_id('TREE_ROOT')
1517
1410
 
1518
 
 
1519
 
def copy_branch(branch_from, to_location, revision=None):
1520
 
    """Copy branch_from into the existing directory to_location.
1521
 
 
1522
 
    revision
1523
 
        If not None, only revisions up to this point will be copied.
1524
 
        The head of the new branch will be that revision.
1525
 
 
1526
 
    to_location
1527
 
        The name of a local directory that exists but is empty.
1528
 
    """
1529
 
    from bzrlib.merge import merge
1530
 
 
1531
 
    assert isinstance(branch_from, Branch)
1532
 
    assert isinstance(to_location, basestring)
1533
 
    
1534
 
    br_to = Branch(to_location, init=True)
1535
 
    br_to.set_root_id(branch_from.get_root_id())
1536
 
    if revision is None:
1537
 
        revno = branch_from.revno()
1538
 
    else:
1539
 
        revno, rev_id = branch_from.get_revision_info(revision)
1540
 
    br_to.update_revisions(branch_from, stop_revision=revno)
1541
 
    merge((to_location, -1), (to_location, 0), this_dir=to_location,
1542
 
          check_clean=False, ignore_zero=True)
1543
 
    br_to.set_parent(branch_from.base)
1544
 
    return br_to
1545
 
 
1546
 
def _trim_namespace(namespace, spec):
1547
 
    full_namespace = namespace + ':'
1548
 
    assert spec.startswith(full_namespace)
1549
 
    return spec[len(full_namespace):]