~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Aaron Bentley
  • Date: 2005-07-26 17:44:20 UTC
  • mto: (1092.1.41) (1185.3.4) (974.1.47)
  • mto: This revision was merged to the branch mainline in revision 1020.
  • Revision ID: abentley@panoramicfeedback.com-20050726174420-ff08fb945ea9cf6b
Implemented merge3 as the default text merge

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
 
18
 
import sys
19
 
import os
 
18
import sys, os
20
19
 
21
20
import bzrlib
22
21
from bzrlib.trace import mutter, note
23
 
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
24
 
     splitpath, \
 
22
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, splitpath, \
25
23
     sha_file, appendpath, file_kind
26
 
 
27
 
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId, \
28
 
     DivergedBranches, NotBranchError
29
 
from bzrlib.textui import show_status
30
 
from bzrlib.revision import Revision
31
 
from bzrlib.delta import compare_trees
32
 
from bzrlib.tree import EmptyTree, RevisionTree
33
 
import bzrlib.xml
34
 
import bzrlib.ui
35
 
 
36
 
 
 
24
from bzrlib.errors import BzrError
37
25
 
38
26
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
39
27
## TODO: Maybe include checks for common corruption of newlines, etc?
40
28
 
41
29
 
42
 
# TODO: Some operations like log might retrieve the same revisions
43
 
# repeatedly to calculate deltas.  We could perhaps have a weakref
44
 
# cache in memory to make this faster.
45
 
 
46
 
# TODO: please move the revision-string syntax stuff out of the branch
47
 
# object; it's clutter
48
 
 
49
30
 
50
31
def find_branch(f, **args):
51
32
    if f and (f.startswith('http://') or f.startswith('https://')):
52
 
        from bzrlib.remotebranch import RemoteBranch
53
 
        return RemoteBranch(f, **args)
 
33
        import remotebranch 
 
34
        return remotebranch.RemoteBranch(f, **args)
54
35
    else:
55
36
        return Branch(f, **args)
56
37
 
57
38
 
58
39
def find_cached_branch(f, cache_root, **args):
59
 
    from bzrlib.remotebranch import RemoteBranch
 
40
    from remotebranch import RemoteBranch
60
41
    br = find_branch(f, **args)
61
42
    def cacheify(br, store_name):
62
 
        from bzrlib.meta_store import CachedStore
 
43
        from meta_store import CachedStore
63
44
        cache_path = os.path.join(cache_root, store_name)
64
45
        os.mkdir(cache_path)
65
46
        new_store = CachedStore(getattr(br, store_name), cache_path)
94
75
        if tail:
95
76
            s.insert(0, tail)
96
77
    else:
 
78
        from errors import NotBranchError
97
79
        raise NotBranchError("path %r is not within branch %r" % (rp, base))
98
80
 
99
81
    return os.sep.join(s)
107
89
    It is not necessary that f exists.
108
90
 
109
91
    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
 
    """
 
92
    run into the root."""
112
93
    if f == None:
113
94
        f = os.getcwd()
114
95
    elif hasattr(os.path, 'realpath'):
127
108
        head, tail = os.path.split(f)
128
109
        if head == f:
129
110
            # reached the root, whatever that may be
130
 
            raise NotBranchError('%s is not in a branch' % orig_f)
 
111
            raise BzrError('%r is not in a branch' % orig_f)
131
112
        f = head
132
 
 
133
 
 
 
113
    
 
114
class DivergedBranches(Exception):
 
115
    def __init__(self, branch1, branch2):
 
116
        self.branch1 = branch1
 
117
        self.branch2 = branch2
 
118
        Exception.__init__(self, "These branches have diverged.")
 
119
 
 
120
 
 
121
class NoSuchRevision(BzrError):
 
122
    def __init__(self, branch, revision):
 
123
        self.branch = branch
 
124
        self.revision = revision
 
125
        msg = "Branch %s has no revision %d" % (branch, revision)
 
126
        BzrError.__init__(self, msg)
134
127
 
135
128
 
136
129
######################################################################
165
158
    def __init__(self, base, init=False, find_root=True):
166
159
        """Create new branch object at a particular location.
167
160
 
168
 
        base -- Base directory for the branch. May be a file:// url.
 
161
        base -- Base directory for the branch.
169
162
        
170
163
        init -- If True, create new control files in a previously
171
164
             unversioned directory.  If False, the branch must already
184
177
        elif find_root:
185
178
            self.base = find_branch_root(base)
186
179
        else:
187
 
            if base.startswith("file://"):
188
 
                base = base[7:]
189
180
            self.base = os.path.realpath(base)
190
181
            if not isdir(self.controlfilename('.')):
 
182
                from errors import NotBranchError
191
183
                raise NotBranchError("not a bzr branch: %s" % quotefn(base),
192
184
                                     ['use "bzr init" to initialize a new working tree',
193
185
                                      'current bzr can only operate from top-of-tree'])
207
199
 
208
200
    def __del__(self):
209
201
        if self._lock_mode or self._lock:
210
 
            from bzrlib.warnings import warn
 
202
            from warnings import warn
211
203
            warn("branch %r was not explicitly unlocked" % self)
212
204
            self._lock.unlock()
213
205
 
 
206
 
 
207
 
214
208
    def lock_write(self):
215
209
        if self._lock_mode:
216
210
            if self._lock_mode != 'w':
217
 
                from bzrlib.errors import LockError
 
211
                from errors import LockError
218
212
                raise LockError("can't upgrade to a write lock from %r" %
219
213
                                self._lock_mode)
220
214
            self._lock_count += 1
226
220
            self._lock_count = 1
227
221
 
228
222
 
 
223
 
229
224
    def lock_read(self):
230
225
        if self._lock_mode:
231
226
            assert self._lock_mode in ('r', 'w'), \
238
233
            self._lock_mode = 'r'
239
234
            self._lock_count = 1
240
235
                        
 
236
 
 
237
            
241
238
    def unlock(self):
242
239
        if not self._lock_mode:
243
 
            from bzrlib.errors import LockError
 
240
            from errors import LockError
244
241
            raise LockError('branch %r is not locked' % (self))
245
242
 
246
243
        if self._lock_count > 1:
250
247
            self._lock = None
251
248
            self._lock_mode = self._lock_count = None
252
249
 
 
250
 
253
251
    def abspath(self, name):
254
252
        """Return absolute filename for something in the branch"""
255
253
        return os.path.join(self.base, name)
256
254
 
 
255
 
257
256
    def relpath(self, path):
258
257
        """Return path relative to this branch of something inside it.
259
258
 
260
259
        Raises an error if path is not in this branch."""
261
260
        return _relpath(self.base, path)
262
261
 
 
262
 
263
263
    def controlfilename(self, file_or_path):
264
264
        """Return location relative to branch."""
265
265
        if isinstance(file_or_path, basestring):
292
292
        else:
293
293
            raise BzrError("invalid controlfile mode %r" % mode)
294
294
 
 
295
 
 
296
 
295
297
    def _make_control(self):
296
298
        from bzrlib.inventory import Inventory
 
299
        from bzrlib.xml import pack_xml
297
300
        
298
301
        os.mkdir(self.controlfilename([]))
299
302
        self.controlfile('README', 'w').write(
309
312
            self.controlfile(f, 'w').write('')
310
313
        mutter('created control directory in ' + self.base)
311
314
 
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)
 
315
        pack_xml(Inventory(gen_root_id()), self.controlfile('inventory','w'))
317
316
 
318
317
 
319
318
    def _check_format(self):
328
327
        # on Windows from Linux and so on.  I think it might be better
329
328
        # to always make all internal files in unix format.
330
329
        fmt = self.controlfile('branch-format', 'r').read()
331
 
        fmt = fmt.replace('\r\n', '\n')
 
330
        fmt.replace('\r\n', '')
332
331
        if fmt != BZR_BRANCH_FORMAT:
333
332
            raise BzrError('sorry, branch format %r not supported' % fmt,
334
333
                           ['use a different bzr version',
354
353
    def read_working_inventory(self):
355
354
        """Read the working inventory."""
356
355
        from bzrlib.inventory import Inventory
 
356
        from bzrlib.xml import unpack_xml
 
357
        from time import time
 
358
        before = time()
357
359
        self.lock_read()
358
360
        try:
359
361
            # ElementTree does its own conversion from UTF-8, so open in
360
362
            # binary.
361
 
            f = self.controlfile('inventory', 'rb')
362
 
            return bzrlib.xml.serializer_v4.read_inventory(f)
 
363
            inv = unpack_xml(Inventory,
 
364
                             self.controlfile('inventory', 'rb'))
 
365
            mutter("loaded inventory of %d items in %f"
 
366
                   % (len(inv), time() - before))
 
367
            return inv
363
368
        finally:
364
369
            self.unlock()
365
370
            
371
376
        will be committed to the next revision.
372
377
        """
373
378
        from bzrlib.atomicfile import AtomicFile
 
379
        from bzrlib.xml import pack_xml
374
380
        
375
381
        self.lock_write()
376
382
        try:
377
383
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
378
384
            try:
379
 
                bzrlib.xml.serializer_v4.write_inventory(inv, f)
 
385
                pack_xml(inv, f)
380
386
                f.commit()
381
387
            finally:
382
388
                f.close()
390
396
                         """Inventory for the working copy.""")
391
397
 
392
398
 
393
 
    def add(self, files, ids=None):
 
399
    def add(self, files, verbose=False, ids=None):
394
400
        """Make files versioned.
395
401
 
396
 
        Note that the command line normally calls smart_add instead,
397
 
        which can automatically recurse.
 
402
        Note that the command line normally calls smart_add instead.
398
403
 
399
404
        This puts the files in the Added state, so that they will be
400
405
        recorded by the next commit.
410
415
        TODO: Perhaps have an option to add the ids even if the files do
411
416
              not (yet) exist.
412
417
 
413
 
        TODO: Perhaps yield the ids and paths as they're added.
 
418
        TODO: Perhaps return the ids of the files?  But then again it
 
419
              is easy to retrieve them if they're needed.
 
420
 
 
421
        TODO: Adding a directory should optionally recurse down and
 
422
              add all non-ignored children.  Perhaps do that in a
 
423
              higher-level method.
414
424
        """
 
425
        from bzrlib.textui import show_status
415
426
        # TODO: Re-adding a file that is removed in the working copy
416
427
        # should probably put it back with the previous ID.
417
428
        if isinstance(files, basestring):
452
463
                    file_id = gen_file_id(f)
453
464
                inv.add_path(f, kind=kind, file_id=file_id)
454
465
 
 
466
                if verbose:
 
467
                    print 'added', quotefn(f)
 
468
 
455
469
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
456
470
 
457
471
            self._write_inventory(inv)
487
501
        is the opposite of add.  Removing it is consistent with most
488
502
        other tools.  Maybe an option.
489
503
        """
 
504
        from bzrlib.textui import show_status
490
505
        ## TODO: Normalize names
491
506
        ## TODO: Remove nested loops; better scalability
492
507
        if isinstance(files, basestring):
567
582
            f.close()
568
583
 
569
584
 
570
 
    def get_revision_xml_file(self, revision_id):
571
 
        """Return XML file object for revision object."""
572
 
        if not revision_id or not isinstance(revision_id, basestring):
573
 
            raise InvalidRevisionId(revision_id)
574
 
 
575
 
        self.lock_read()
576
 
        try:
577
 
            try:
578
 
                return self.revision_store[revision_id]
579
 
            except KeyError:
580
 
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
581
 
        finally:
582
 
            self.unlock()
583
 
 
584
 
 
585
 
    #deprecated
586
 
    get_revision_xml = get_revision_xml_file
587
 
 
588
 
 
589
585
    def get_revision(self, revision_id):
590
586
        """Return the Revision object for a named revision"""
591
 
        xml_file = self.get_revision_xml_file(revision_id)
 
587
        from bzrlib.revision import Revision
 
588
        from bzrlib.xml import unpack_xml
592
589
 
 
590
        self.lock_read()
593
591
        try:
594
 
            r = bzrlib.xml.serializer_v4.read_revision(xml_file)
595
 
        except SyntaxError, e:
596
 
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
597
 
                                         [revision_id,
598
 
                                          str(e)])
 
592
            if not revision_id or not isinstance(revision_id, basestring):
 
593
                raise ValueError('invalid revision-id: %r' % revision_id)
 
594
            r = unpack_xml(Revision, self.revision_store[revision_id])
 
595
        finally:
 
596
            self.unlock()
599
597
            
600
598
        assert r.revision_id == revision_id
601
599
        return r
602
 
 
603
 
 
604
 
    def get_revision_delta(self, revno):
605
 
        """Return the delta for one revision.
606
 
 
607
 
        The delta is relative to its mainline predecessor, or the
608
 
        empty tree for revision 1.
609
 
        """
610
 
        assert isinstance(revno, int)
611
 
        rh = self.revision_history()
612
 
        if not (1 <= revno <= len(rh)):
613
 
            raise InvalidRevisionNumber(revno)
614
 
 
615
 
        # revno is 1-based; list is 0-based
616
 
 
617
 
        new_tree = self.revision_tree(rh[revno-1])
618
 
        if revno == 1:
619
 
            old_tree = EmptyTree()
620
 
        else:
621
 
            old_tree = self.revision_tree(rh[revno-2])
622
 
 
623
 
        return compare_trees(old_tree, new_tree)
624
 
 
625
600
        
626
601
 
627
602
    def get_revision_sha1(self, revision_id):
632
607
        # the revision, (add signatures/remove signatures) and still
633
608
        # have all hash pointers stay consistent.
634
609
        # But for now, just hash the contents.
635
 
        return bzrlib.osutils.sha_file(self.get_revision_xml(revision_id))
 
610
        return sha_file(self.revision_store[revision_id])
636
611
 
637
612
 
638
613
    def get_inventory(self, inventory_id):
642
617
               parameter which can be either an integer revno or a
643
618
               string hash."""
644
619
        from bzrlib.inventory import Inventory
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
 
620
        from bzrlib.xml import unpack_xml
 
621
 
 
622
        return unpack_xml(Inventory, self.inventory_store[inventory_id])
655
623
            
656
624
 
657
625
    def get_inventory_sha1(self, inventory_id):
658
626
        """Return the sha1 hash of the inventory entry
659
627
        """
660
 
        return sha_file(self.get_inventory_xml(inventory_id))
 
628
        return sha_file(self.inventory_store[inventory_id])
661
629
 
662
630
 
663
631
    def get_revision_inventory(self, revision_id):
687
655
 
688
656
    def common_ancestor(self, other, self_revno=None, other_revno=None):
689
657
        """
690
 
        >>> from bzrlib.commit import commit
 
658
        >>> import commit
691
659
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
692
660
        >>> sb.common_ancestor(sb) == (None, None)
693
661
        True
694
 
        >>> commit(sb, "Committing first revision", verbose=False)
 
662
        >>> commit.commit(sb, "Committing first revision", verbose=False)
695
663
        >>> sb.common_ancestor(sb)[0]
696
664
        1
697
665
        >>> clone = sb.clone()
698
 
        >>> commit(sb, "Committing second revision", verbose=False)
 
666
        >>> commit.commit(sb, "Committing second revision", verbose=False)
699
667
        >>> sb.common_ancestor(sb)[0]
700
668
        2
701
669
        >>> sb.common_ancestor(clone)[0]
702
670
        1
703
 
        >>> commit(clone, "Committing divergent second revision", 
 
671
        >>> commit.commit(clone, "Committing divergent second revision", 
704
672
        ...               verbose=False)
705
673
        >>> sb.common_ancestor(clone)[0]
706
674
        1
729
697
                return r+1, my_history[r]
730
698
        return None, None
731
699
 
 
700
    def enum_history(self, direction):
 
701
        """Return (revno, revision_id) for history of branch.
 
702
 
 
703
        direction
 
704
            'forward' is from earliest to latest
 
705
            'reverse' is from latest to earliest
 
706
        """
 
707
        rh = self.revision_history()
 
708
        if direction == 'forward':
 
709
            i = 1
 
710
            for rid in rh:
 
711
                yield i, rid
 
712
                i += 1
 
713
        elif direction == 'reverse':
 
714
            i = len(rh)
 
715
            while i > 0:
 
716
                yield i, rh[i-1]
 
717
                i -= 1
 
718
        else:
 
719
            raise ValueError('invalid history direction', direction)
 
720
 
732
721
 
733
722
    def revno(self):
734
723
        """Return current revision number for this branch.
749
738
            return None
750
739
 
751
740
 
752
 
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
 
741
    def missing_revisions(self, other, stop_revision=None):
753
742
        """
754
743
        If self and other have not diverged, return a list of the revisions
755
744
        present in other, but missing from self.
788
777
        if stop_revision is None:
789
778
            stop_revision = other_len
790
779
        elif stop_revision > other_len:
791
 
            raise bzrlib.errors.NoSuchRevision(self, stop_revision)
 
780
            raise NoSuchRevision(self, stop_revision)
792
781
        
793
782
        return other_history[self_len:stop_revision]
794
783
 
795
784
 
796
785
    def update_revisions(self, other, stop_revision=None):
797
786
        """Pull in all new revisions from other branch.
 
787
        
 
788
        >>> from bzrlib.commit import commit
 
789
        >>> bzrlib.trace.silent = True
 
790
        >>> br1 = ScratchBranch(files=['foo', 'bar'])
 
791
        >>> br1.add('foo')
 
792
        >>> br1.add('bar')
 
793
        >>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
 
794
        >>> br2 = ScratchBranch()
 
795
        >>> br2.update_revisions(br1)
 
796
        Added 2 texts.
 
797
        Added 1 inventories.
 
798
        Added 1 revisions.
 
799
        >>> br2.revision_history()
 
800
        [u'REVISION-ID-1']
 
801
        >>> br2.update_revisions(br1)
 
802
        Added 0 texts.
 
803
        Added 0 inventories.
 
804
        Added 0 revisions.
 
805
        >>> br1.text_store.total_size() == br2.text_store.total_size()
 
806
        True
798
807
        """
799
 
        from bzrlib.fetch import greedy_fetch
800
 
        from bzrlib.revision import get_intervening_revisions
801
 
 
802
 
        pb = bzrlib.ui.ui_factory.progress_bar()
 
808
        from bzrlib.progress import ProgressBar
 
809
 
 
810
        pb = ProgressBar()
 
811
 
803
812
        pb.update('comparing histories')
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):
 
813
        revision_ids = self.missing_revisions(other, stop_revision)
 
814
 
823
815
        if hasattr(other.revision_store, "prefetch"):
824
816
            other.revision_store.prefetch(revision_ids)
825
817
        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
 
818
            inventory_ids = [other.get_revision(r).inventory_id
 
819
                             for r in revision_ids]
833
820
            other.inventory_store.prefetch(inventory_ids)
834
 
 
835
 
        if pb is None:
836
 
            pb = bzrlib.ui.ui_factory.progress_bar()
837
821
                
838
822
        revisions = []
839
823
        needed_texts = set()
840
824
        i = 0
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
 
 
 
825
        for rev_id in revision_ids:
 
826
            i += 1
 
827
            pb.update('fetching revision', i, len(revision_ids))
 
828
            rev = other.get_revision(rev_id)
851
829
            revisions.append(rev)
852
830
            inv = other.get_inventory(str(rev.inventory_id))
853
831
            for key, entry in inv.iter_entries():
858
836
 
859
837
        pb.clear()
860
838
                    
861
 
        count, cp_fail = self.text_store.copy_multi(other.text_store, 
862
 
                                                    needed_texts)
863
 
        #print "Added %d texts." % count 
 
839
        count = self.text_store.copy_multi(other.text_store, needed_texts)
 
840
        print "Added %d texts." % count 
864
841
        inventory_ids = [ f.inventory_id for f in revisions ]
865
 
        count, cp_fail = self.inventory_store.copy_multi(other.inventory_store, 
866
 
                                                         inventory_ids)
867
 
        #print "Added %d inventories." % count 
 
842
        count = self.inventory_store.copy_multi(other.inventory_store, 
 
843
                                                inventory_ids)
 
844
        print "Added %d inventories." % count 
868
845
        revision_ids = [ f.revision_id for f in revisions]
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
 
 
 
846
        count = self.revision_store.copy_multi(other.revision_store, 
 
847
                                               revision_ids)
 
848
        for revision_id in revision_ids:
 
849
            self.append_revision(revision_id)
 
850
        print "Added %d revisions." % count
 
851
                    
 
852
        
877
853
    def commit(self, *args, **kw):
878
854
        from bzrlib.commit import commit
879
855
        commit(self, *args, **kw)
881
857
 
882
858
    def lookup_revision(self, revision):
883
859
        """Return the revision identifier for a given revision information."""
884
 
        revno, info = self._get_revision_info(revision)
 
860
        revno, info = self.get_revision_info(revision)
885
861
        return info
886
862
 
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
863
    def get_revision_info(self, revision):
898
864
        """Return (revno, revision id) for revision identifier.
899
865
 
902
868
        revision can also be a string, in which case it is parsed for something like
903
869
            'date:' or 'revid:' etc.
904
870
        """
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
871
        if revision is None:
934
872
            return 0, None
935
873
        revno = None
939
877
            pass
940
878
        revs = self.revision_history()
941
879
        if isinstance(revision, int):
 
880
            if revision == 0:
 
881
                return 0, None
 
882
            # Mabye we should do this first, but we don't need it if revision == 0
942
883
            if revision < 0:
943
884
                revno = len(revs) + revision + 1
944
885
            else:
945
886
                revno = revision
946
 
            rev_id = self.get_rev_id(revno, revs)
947
887
        elif isinstance(revision, basestring):
948
888
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
949
889
                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)
 
890
                    revno = func(self, revs, revision)
956
891
                    break
957
892
            else:
958
 
                raise BzrError('No namespace registered for string: %r' %
959
 
                               revision)
960
 
        else:
961
 
            raise TypeError('Unhandled revision type %s' % revision)
 
893
                raise BzrError('No namespace registered for string: %r' % revision)
962
894
 
963
 
        if revno is None:
964
 
            if rev_id is None:
965
 
                raise bzrlib.errors.NoSuchRevision(self, revision)
966
 
        return revno, rev_id
 
895
        if revno is None or revno <= 0 or revno > len(revs):
 
896
            raise BzrError("no such revision %s" % revision)
 
897
        return revno, revs[revno-1]
967
898
 
968
899
    def _namespace_revno(self, revs, revision):
969
900
        """Lookup a revision by revision number"""
970
901
        assert revision.startswith('revno:')
971
902
        try:
972
 
            return (int(revision[6:]),)
 
903
            return int(revision[6:])
973
904
        except ValueError:
974
905
            return None
975
906
    REVISION_NAMESPACES['revno:'] = _namespace_revno
976
907
 
977
908
    def _namespace_revid(self, revs, revision):
978
909
        assert revision.startswith('revid:')
979
 
        rev_id = revision[len('revid:'):]
980
910
        try:
981
 
            return revs.index(rev_id) + 1, rev_id
 
911
            return revs.index(revision[6:]) + 1
982
912
        except ValueError:
983
 
            return None, rev_id
 
913
            return None
984
914
    REVISION_NAMESPACES['revid:'] = _namespace_revid
985
915
 
986
916
    def _namespace_last(self, revs, revision):
988
918
        try:
989
919
            offset = int(revision[5:])
990
920
        except ValueError:
991
 
            return (None,)
 
921
            return None
992
922
        else:
993
923
            if offset <= 0:
994
924
                raise BzrError('You must supply a positive value for --revision last:XXX')
995
 
            return (len(revs) - offset + 1,)
 
925
            return len(revs) - offset + 1
996
926
    REVISION_NAMESPACES['last:'] = _namespace_last
997
927
 
998
928
    def _namespace_tag(self, revs, revision):
1073
1003
                # TODO: Handle timezone.
1074
1004
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1075
1005
                if first >= dt and (last is None or dt >= last):
1076
 
                    return (i+1,)
 
1006
                    return i+1
1077
1007
        else:
1078
1008
            for i in range(len(revs)):
1079
1009
                r = self.get_revision(revs[i])
1080
1010
                # TODO: Handle timezone.
1081
1011
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1082
1012
                if first <= dt and (last is None or dt <= last):
1083
 
                    return (i+1,)
 
1013
                    return i+1
1084
1014
    REVISION_NAMESPACES['date:'] = _namespace_date
1085
1015
 
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
1016
    def revision_tree(self, revision_id):
1107
1017
        """Return Tree for a revision on this branch.
1108
1018
 
1109
1019
        `revision_id` may be None for the null revision, in which case
1110
1020
        an `EmptyTree` is returned."""
 
1021
        from bzrlib.tree import EmptyTree, RevisionTree
1111
1022
        # TODO: refactor this to use an existing revision object
1112
1023
        # so we don't need to read it in twice.
1113
1024
        if revision_id == None:
1114
 
            return EmptyTree()
 
1025
            return EmptyTree(self.get_root_id())
1115
1026
        else:
1116
1027
            inv = self.get_revision_inventory(revision_id)
1117
1028
            return RevisionTree(self.text_store, inv)
1119
1030
 
1120
1031
    def working_tree(self):
1121
1032
        """Return a `Tree` for the working copy."""
1122
 
        from bzrlib.workingtree import WorkingTree
 
1033
        from workingtree import WorkingTree
1123
1034
        return WorkingTree(self.base, self.read_working_inventory())
1124
1035
 
1125
1036
 
1128
1039
 
1129
1040
        If there are no revisions yet, return an `EmptyTree`.
1130
1041
        """
 
1042
        from bzrlib.tree import EmptyTree, RevisionTree
1131
1043
        r = self.last_patch()
1132
1044
        if r == None:
1133
 
            return EmptyTree()
 
1045
            return EmptyTree(self.get_root_id())
1134
1046
        else:
1135
1047
            return RevisionTree(self.text_store, self.get_revision_inventory(r))
1136
1048
 
1171
1083
 
1172
1084
            inv.rename(file_id, to_dir_id, to_tail)
1173
1085
 
 
1086
            print "%s => %s" % (from_rel, to_rel)
 
1087
 
1174
1088
            from_abs = self.abspath(from_rel)
1175
1089
            to_abs = self.abspath(to_rel)
1176
1090
            try:
1195
1109
 
1196
1110
        Note that to_name is only the last component of the new name;
1197
1111
        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
1112
        """
1202
 
        result = []
1203
1113
        self.lock_write()
1204
1114
        try:
1205
1115
            ## TODO: Option to move IDs only
1240
1150
            for f in from_paths:
1241
1151
                name_tail = splitpath(f)[-1]
1242
1152
                dest_path = appendpath(to_name, name_tail)
1243
 
                result.append((f, dest_path))
 
1153
                print "%s => %s" % (f, dest_path)
1244
1154
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1245
1155
                try:
1246
1156
                    os.rename(self.abspath(f), self.abspath(dest_path))
1252
1162
        finally:
1253
1163
            self.unlock()
1254
1164
 
1255
 
        return result
1256
 
 
1257
1165
 
1258
1166
    def revert(self, filenames, old_tree=None, backups=True):
1259
1167
        """Restore selected files to the versions from a previous tree.
1341
1249
            self.unlock()
1342
1250
 
1343
1251
 
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
1252
 
1395
1253
class ScratchBranch(Branch):
1396
1254
    """Special test class: a branch that cleans up after itself.
1438
1296
        os.rmdir(base)
1439
1297
        copytree(self.base, base, symlinks=True)
1440
1298
        return ScratchBranch(base=base)
1441
 
 
1442
 
 
1443
1299
        
1444
1300
    def __del__(self):
1445
1301
        self.destroy()
1515
1371
    """Return a new tree-root file id."""
1516
1372
    return gen_file_id('TREE_ROOT')
1517
1373
 
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):]