/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

remove unneeded shebangs

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
######################################################################
162
165
    def __init__(self, base, init=False, find_root=True):
163
166
        """Create new branch object at a particular location.
164
167
 
165
 
        base -- Base directory for the branch.
 
168
        base -- Base directory for the branch. May be a file:// url.
166
169
        
167
170
        init -- If True, create new control files in a previously
168
171
             unversioned directory.  If False, the branch must already
181
184
        elif find_root:
182
185
            self.base = find_branch_root(base)
183
186
        else:
 
187
            if base.startswith("file://"):
 
188
                base = base[7:]
184
189
            self.base = os.path.realpath(base)
185
190
            if not isdir(self.controlfilename('.')):
186
 
                from errors import NotBranchError
187
191
                raise NotBranchError("not a bzr branch: %s" % quotefn(base),
188
192
                                     ['use "bzr init" to initialize a new working tree',
189
193
                                      'current bzr can only operate from top-of-tree'])
203
207
 
204
208
    def __del__(self):
205
209
        if self._lock_mode or self._lock:
206
 
            from warnings import warn
 
210
            from bzrlib.warnings import warn
207
211
            warn("branch %r was not explicitly unlocked" % self)
208
212
            self._lock.unlock()
209
213
 
210
 
 
211
 
 
212
214
    def lock_write(self):
213
215
        if self._lock_mode:
214
216
            if self._lock_mode != 'w':
215
 
                from errors import LockError
 
217
                from bzrlib.errors import LockError
216
218
                raise LockError("can't upgrade to a write lock from %r" %
217
219
                                self._lock_mode)
218
220
            self._lock_count += 1
224
226
            self._lock_count = 1
225
227
 
226
228
 
227
 
 
228
229
    def lock_read(self):
229
230
        if self._lock_mode:
230
231
            assert self._lock_mode in ('r', 'w'), \
237
238
            self._lock_mode = 'r'
238
239
            self._lock_count = 1
239
240
                        
240
 
 
241
 
            
242
241
    def unlock(self):
243
242
        if not self._lock_mode:
244
 
            from errors import LockError
 
243
            from bzrlib.errors import LockError
245
244
            raise LockError('branch %r is not locked' % (self))
246
245
 
247
246
        if self._lock_count > 1:
251
250
            self._lock = None
252
251
            self._lock_mode = self._lock_count = None
253
252
 
254
 
 
255
253
    def abspath(self, name):
256
254
        """Return absolute filename for something in the branch"""
257
255
        return os.path.join(self.base, name)
258
256
 
259
 
 
260
257
    def relpath(self, path):
261
258
        """Return path relative to this branch of something inside it.
262
259
 
263
260
        Raises an error if path is not in this branch."""
264
261
        return _relpath(self.base, path)
265
262
 
266
 
 
267
263
    def controlfilename(self, file_or_path):
268
264
        """Return location relative to branch."""
269
265
        if isinstance(file_or_path, basestring):
296
292
        else:
297
293
            raise BzrError("invalid controlfile mode %r" % mode)
298
294
 
299
 
 
300
 
 
301
295
    def _make_control(self):
302
296
        from bzrlib.inventory import Inventory
303
 
        from bzrlib.xml import pack_xml
304
297
        
305
298
        os.mkdir(self.controlfilename([]))
306
299
        self.controlfile('README', 'w').write(
316
309
            self.controlfile(f, 'w').write('')
317
310
        mutter('created control directory in ' + self.base)
318
311
 
319
 
        pack_xml(Inventory(gen_root_id()), self.controlfile('inventory','w'))
 
312
        # if we want per-tree root ids then this is the place to set
 
313
        # them; they're not needed for now and so ommitted for
 
314
        # simplicity.
 
315
        f = self.controlfile('inventory','w')
 
316
        bzrlib.xml.serializer_v4.write_inventory(Inventory(), f)
320
317
 
321
318
 
322
319
    def _check_format(self):
331
328
        # on Windows from Linux and so on.  I think it might be better
332
329
        # to always make all internal files in unix format.
333
330
        fmt = self.controlfile('branch-format', 'r').read()
334
 
        fmt.replace('\r\n', '')
 
331
        fmt = fmt.replace('\r\n', '\n')
335
332
        if fmt != BZR_BRANCH_FORMAT:
336
333
            raise BzrError('sorry, branch format %r not supported' % fmt,
337
334
                           ['use a different bzr version',
357
354
    def read_working_inventory(self):
358
355
        """Read the working inventory."""
359
356
        from bzrlib.inventory import Inventory
360
 
        from bzrlib.xml import unpack_xml
361
 
        from time import time
362
 
        before = time()
363
357
        self.lock_read()
364
358
        try:
365
359
            # ElementTree does its own conversion from UTF-8, so open in
366
360
            # 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
 
361
            f = self.controlfile('inventory', 'rb')
 
362
            return bzrlib.xml.serializer_v4.read_inventory(f)
372
363
        finally:
373
364
            self.unlock()
374
365
            
380
371
        will be committed to the next revision.
381
372
        """
382
373
        from bzrlib.atomicfile import AtomicFile
383
 
        from bzrlib.xml import pack_xml
384
374
        
385
375
        self.lock_write()
386
376
        try:
387
377
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
388
378
            try:
389
 
                pack_xml(inv, f)
 
379
                bzrlib.xml.serializer_v4.write_inventory(inv, f)
390
380
                f.commit()
391
381
            finally:
392
382
                f.close()
400
390
                         """Inventory for the working copy.""")
401
391
 
402
392
 
403
 
    def add(self, files, verbose=False, ids=None):
 
393
    def add(self, files, ids=None):
404
394
        """Make files versioned.
405
395
 
406
 
        Note that the command line normally calls smart_add instead.
 
396
        Note that the command line normally calls smart_add instead,
 
397
        which can automatically recurse.
407
398
 
408
399
        This puts the files in the Added state, so that they will be
409
400
        recorded by the next commit.
419
410
        TODO: Perhaps have an option to add the ids even if the files do
420
411
              not (yet) exist.
421
412
 
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.
 
413
        TODO: Perhaps yield the ids and paths as they're added.
428
414
        """
429
415
        # TODO: Re-adding a file that is removed in the working copy
430
416
        # should probably put it back with the previous ID.
466
452
                    file_id = gen_file_id(f)
467
453
                inv.add_path(f, kind=kind, file_id=file_id)
468
454
 
469
 
                if verbose:
470
 
                    print 'added', quotefn(f)
471
 
 
472
455
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
473
456
 
474
457
            self._write_inventory(inv)
584
567
            f.close()
585
568
 
586
569
 
587
 
    def get_revision_xml(self, revision_id):
 
570
    def get_revision_xml_file(self, revision_id):
588
571
        """Return XML file object for revision object."""
589
572
        if not revision_id or not isinstance(revision_id, basestring):
590
573
            raise InvalidRevisionId(revision_id)
593
576
        try:
594
577
            try:
595
578
                return self.revision_store[revision_id]
596
 
            except IndexError:
597
 
                raise bzrlib.errors.NoSuchRevision(revision_id)
 
579
            except (IndexError, KeyError):
 
580
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
598
581
        finally:
599
582
            self.unlock()
600
583
 
601
584
 
 
585
    #deprecated
 
586
    get_revision_xml = get_revision_xml_file
 
587
 
 
588
 
602
589
    def get_revision(self, revision_id):
603
590
        """Return the Revision object for a named revision"""
604
 
        xml_file = self.get_revision_xml(revision_id)
 
591
        xml_file = self.get_revision_xml_file(revision_id)
605
592
 
606
593
        try:
607
 
            r = unpack_xml(Revision, xml_file)
 
594
            r = bzrlib.xml.serializer_v4.read_revision(xml_file)
608
595
        except SyntaxError, e:
609
596
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
610
597
                                         [revision_id,
655
642
               parameter which can be either an integer revno or a
656
643
               string hash."""
657
644
        from bzrlib.inventory import Inventory
658
 
        from bzrlib.xml import unpack_xml
659
 
 
660
 
        return unpack_xml(Inventory, self.inventory_store[inventory_id])
 
645
 
 
646
        f = self.get_inventory_xml_file(inventory_id)
 
647
        return bzrlib.xml.serializer_v4.read_inventory(f)
 
648
 
 
649
 
 
650
    def get_inventory_xml(self, inventory_id):
 
651
        """Get inventory XML as a file object."""
 
652
        return self.inventory_store[inventory_id]
 
653
 
 
654
    get_inventory_xml_file = get_inventory_xml
661
655
            
662
656
 
663
657
    def get_inventory_sha1(self, inventory_id):
664
658
        """Return the sha1 hash of the inventory entry
665
659
        """
666
 
        return sha_file(self.inventory_store[inventory_id])
 
660
        return sha_file(self.get_inventory_xml(inventory_id))
667
661
 
668
662
 
669
663
    def get_revision_inventory(self, revision_id):
693
687
 
694
688
    def common_ancestor(self, other, self_revno=None, other_revno=None):
695
689
        """
696
 
        >>> import commit
 
690
        >>> from bzrlib.commit import commit
697
691
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
698
692
        >>> sb.common_ancestor(sb) == (None, None)
699
693
        True
700
 
        >>> commit.commit(sb, "Committing first revision", verbose=False)
 
694
        >>> commit(sb, "Committing first revision", verbose=False)
701
695
        >>> sb.common_ancestor(sb)[0]
702
696
        1
703
697
        >>> clone = sb.clone()
704
 
        >>> commit.commit(sb, "Committing second revision", verbose=False)
 
698
        >>> commit(sb, "Committing second revision", verbose=False)
705
699
        >>> sb.common_ancestor(sb)[0]
706
700
        2
707
701
        >>> sb.common_ancestor(clone)[0]
708
702
        1
709
 
        >>> commit.commit(clone, "Committing divergent second revision", 
 
703
        >>> commit(clone, "Committing divergent second revision", 
710
704
        ...               verbose=False)
711
705
        >>> sb.common_ancestor(clone)[0]
712
706
        1
755
749
            return None
756
750
 
757
751
 
758
 
    def missing_revisions(self, other, stop_revision=None):
 
752
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
759
753
        """
760
754
        If self and other have not diverged, return a list of the revisions
761
755
        present in other, but missing from self.
794
788
        if stop_revision is None:
795
789
            stop_revision = other_len
796
790
        elif stop_revision > other_len:
797
 
            raise NoSuchRevision(self, stop_revision)
 
791
            raise bzrlib.errors.NoSuchRevision(self, stop_revision)
798
792
        
799
793
        return other_history[self_len:stop_revision]
800
794
 
801
795
 
802
796
    def update_revisions(self, other, stop_revision=None):
803
797
        """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
798
        """
825
 
        from bzrlib.progress import ProgressBar
826
 
 
827
 
        pb = ProgressBar()
828
 
 
 
799
        from bzrlib.fetch import greedy_fetch
 
800
        from bzrlib.revision import get_intervening_revisions
 
801
 
 
802
        pb = bzrlib.ui.ui_factory.progress_bar()
829
803
        pb.update('comparing histories')
830
 
        revision_ids = self.missing_revisions(other, stop_revision)
831
 
 
 
804
        if stop_revision is None:
 
805
            other_revision = other.last_patch()
 
806
        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
 
 
819
        self.append_revision(*revision_ids)
 
820
        pb.clear()
 
821
 
 
822
    def install_revisions(self, other, revision_ids, pb):
832
823
        if hasattr(other.revision_store, "prefetch"):
833
824
            other.revision_store.prefetch(revision_ids)
834
825
        if hasattr(other.inventory_store, "prefetch"):
835
 
            inventory_ids = [other.get_revision(r).inventory_id
836
 
                             for r in revision_ids]
 
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
837
833
            other.inventory_store.prefetch(inventory_ids)
 
834
 
 
835
        if pb is None:
 
836
            pb = bzrlib.ui.ui_factory.progress_bar()
838
837
                
839
838
        revisions = []
840
839
        needed_texts = set()
841
840
        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)
 
841
 
 
842
        failures = set()
 
843
        for i, rev_id in enumerate(revision_ids):
 
844
            pb.update('fetching revision', i+1, len(revision_ids))
 
845
            try:
 
846
                rev = other.get_revision(rev_id)
 
847
            except bzrlib.errors.NoSuchRevision:
 
848
                failures.add(rev_id)
 
849
                continue
 
850
 
846
851
            revisions.append(rev)
847
852
            inv = other.get_inventory(str(rev.inventory_id))
848
853
            for key, entry in inv.iter_entries():
853
858
 
854
859
        pb.clear()
855
860
                    
856
 
        count = self.text_store.copy_multi(other.text_store, needed_texts)
857
 
        print "Added %d texts." % count 
 
861
        count, cp_fail = self.text_store.copy_multi(other.text_store, 
 
862
                                                    needed_texts)
 
863
        #print "Added %d texts." % count 
858
864
        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 
 
865
        count, cp_fail = self.inventory_store.copy_multi(other.inventory_store, 
 
866
                                                         inventory_ids)
 
867
        #print "Added %d inventories." % count 
862
868
        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
 
        
 
869
 
 
870
        count, cp_fail = self.revision_store.copy_multi(other.revision_store, 
 
871
                                                          revision_ids,
 
872
                                                          permit_failure=True)
 
873
        assert len(cp_fail) == 0 
 
874
        return count, failures
 
875
       
 
876
 
870
877
    def commit(self, *args, **kw):
871
878
        from bzrlib.commit import commit
872
879
        commit(self, *args, **kw)
874
881
 
875
882
    def lookup_revision(self, revision):
876
883
        """Return the revision identifier for a given revision information."""
877
 
        revno, info = self.get_revision_info(revision)
 
884
        revno, info = self._get_revision_info(revision)
878
885
        return info
879
886
 
 
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
 
880
897
    def get_revision_info(self, revision):
881
898
        """Return (revno, revision id) for revision identifier.
882
899
 
885
902
        revision can also be a string, in which case it is parsed for something like
886
903
            'date:' or 'revid:' etc.
887
904
        """
 
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
        
888
933
        if revision is None:
889
934
            return 0, None
890
935
        revno = None
894
939
            pass
895
940
        revs = self.revision_history()
896
941
        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
942
            if revision < 0:
901
943
                revno = len(revs) + revision + 1
902
944
            else:
903
945
                revno = revision
 
946
            rev_id = self.get_rev_id(revno, revs)
904
947
        elif isinstance(revision, basestring):
905
948
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
906
949
                if revision.startswith(prefix):
907
 
                    revno = func(self, revs, revision)
 
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)
908
956
                    break
909
957
            else:
910
 
                raise BzrError('No namespace registered for string: %r' % revision)
 
958
                raise BzrError('No namespace registered for string: %r' %
 
959
                               revision)
 
960
        else:
 
961
            raise TypeError('Unhandled revision type %s' % revision)
911
962
 
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]
 
963
        if revno is None:
 
964
            if rev_id is None:
 
965
                raise bzrlib.errors.NoSuchRevision(self, revision)
 
966
        return revno, rev_id
915
967
 
916
968
    def _namespace_revno(self, revs, revision):
917
969
        """Lookup a revision by revision number"""
918
970
        assert revision.startswith('revno:')
919
971
        try:
920
 
            return int(revision[6:])
 
972
            return (int(revision[6:]),)
921
973
        except ValueError:
922
974
            return None
923
975
    REVISION_NAMESPACES['revno:'] = _namespace_revno
924
976
 
925
977
    def _namespace_revid(self, revs, revision):
926
978
        assert revision.startswith('revid:')
 
979
        rev_id = revision[len('revid:'):]
927
980
        try:
928
 
            return revs.index(revision[6:]) + 1
 
981
            return revs.index(rev_id) + 1, rev_id
929
982
        except ValueError:
930
 
            return None
 
983
            return None, rev_id
931
984
    REVISION_NAMESPACES['revid:'] = _namespace_revid
932
985
 
933
986
    def _namespace_last(self, revs, revision):
935
988
        try:
936
989
            offset = int(revision[5:])
937
990
        except ValueError:
938
 
            return None
 
991
            return (None,)
939
992
        else:
940
993
            if offset <= 0:
941
994
                raise BzrError('You must supply a positive value for --revision last:XXX')
942
 
            return len(revs) - offset + 1
 
995
            return (len(revs) - offset + 1,)
943
996
    REVISION_NAMESPACES['last:'] = _namespace_last
944
997
 
945
998
    def _namespace_tag(self, revs, revision):
1020
1073
                # TODO: Handle timezone.
1021
1074
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1022
1075
                if first >= dt and (last is None or dt >= last):
1023
 
                    return i+1
 
1076
                    return (i+1,)
1024
1077
        else:
1025
1078
            for i in range(len(revs)):
1026
1079
                r = self.get_revision(revs[i])
1027
1080
                # TODO: Handle timezone.
1028
1081
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1029
1082
                if first <= dt and (last is None or dt <= last):
1030
 
                    return i+1
 
1083
                    return (i+1,)
1031
1084
    REVISION_NAMESPACES['date:'] = _namespace_date
1032
1085
 
 
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
 
1033
1106
    def revision_tree(self, revision_id):
1034
1107
        """Return Tree for a revision on this branch.
1035
1108
 
1046
1119
 
1047
1120
    def working_tree(self):
1048
1121
        """Return a `Tree` for the working copy."""
1049
 
        from workingtree import WorkingTree
 
1122
        from bzrlib.workingtree import WorkingTree
1050
1123
        return WorkingTree(self.base, self.read_working_inventory())
1051
1124
 
1052
1125
 
1098
1171
 
1099
1172
            inv.rename(file_id, to_dir_id, to_tail)
1100
1173
 
1101
 
            print "%s => %s" % (from_rel, to_rel)
1102
 
 
1103
1174
            from_abs = self.abspath(from_rel)
1104
1175
            to_abs = self.abspath(to_rel)
1105
1176
            try:
1124
1195
 
1125
1196
        Note that to_name is only the last component of the new name;
1126
1197
        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.
1127
1201
        """
 
1202
        result = []
1128
1203
        self.lock_write()
1129
1204
        try:
1130
1205
            ## TODO: Option to move IDs only
1165
1240
            for f in from_paths:
1166
1241
                name_tail = splitpath(f)[-1]
1167
1242
                dest_path = appendpath(to_name, name_tail)
1168
 
                print "%s => %s" % (f, dest_path)
 
1243
                result.append((f, dest_path))
1169
1244
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1170
1245
                try:
1171
1246
                    os.rename(self.abspath(f), self.abspath(dest_path))
1177
1252
        finally:
1178
1253
            self.unlock()
1179
1254
 
 
1255
        return result
 
1256
 
1180
1257
 
1181
1258
    def revert(self, filenames, old_tree=None, backups=True):
1182
1259
        """Restore selected files to the versions from a previous tree.
1264
1341
            self.unlock()
1265
1342
 
1266
1343
 
 
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
 
1267
1394
 
1268
1395
class ScratchBranch(Branch):
1269
1396
    """Special test class: a branch that cleans up after itself.
1311
1438
        os.rmdir(base)
1312
1439
        copytree(self.base, base, symlinks=True)
1313
1440
        return ScratchBranch(base=base)
 
1441
 
 
1442
 
1314
1443
        
1315
1444
    def __del__(self):
1316
1445
        self.destroy()
1386
1515
    """Return a new tree-root file id."""
1387
1516
    return gen_file_id('TREE_ROOT')
1388
1517
 
 
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):]