/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2005-09-16 08:49:31 UTC
  • Revision ID: mbp@sourcefrog.net-20050916084931-b6792a121f4f8ae9
- add Branch constructor option to relax version check 
  to help with upgrade process

- tidy up imports

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
 
18
18
import sys
19
19
import os
 
20
from cStringIO import StringIO
20
21
 
21
22
import bzrlib
22
23
from bzrlib.trace import mutter, note
23
24
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
24
25
     splitpath, \
25
26
     sha_file, appendpath, file_kind
26
 
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId
27
 
import bzrlib.errors
 
27
 
 
28
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
 
29
                           NoSuchRevision, HistoryMissing, NotBranchError)
28
30
from bzrlib.textui import show_status
29
 
from bzrlib.revision import Revision
30
 
from bzrlib.xml import unpack_xml
 
31
from bzrlib.revision import Revision, validate_revision_id
31
32
from bzrlib.delta import compare_trees
32
33
from bzrlib.tree import EmptyTree, RevisionTree
33
 
        
34
 
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
 
34
from bzrlib.inventory import Inventory
 
35
from bzrlib.weavestore import WeaveStore
 
36
from bzrlib.store import ImmutableStore
 
37
import bzrlib.xml5
 
38
import bzrlib.ui
 
39
 
 
40
 
 
41
INVENTORY_FILEID = '__inventory'
 
42
ANCESTRY_FILEID = '__ancestry'
 
43
 
 
44
 
 
45
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
 
46
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
35
47
## TODO: Maybe include checks for common corruption of newlines, etc?
36
48
 
37
49
 
38
50
# TODO: Some operations like log might retrieve the same revisions
39
51
# repeatedly to calculate deltas.  We could perhaps have a weakref
40
 
# cache in memory to make this faster.
 
52
# cache in memory to make this faster.  In general anything can be
 
53
# cached in memory between lock and unlock operations.
 
54
 
 
55
# TODO: please move the revision-string syntax stuff out of the branch
 
56
# object; it's clutter
41
57
 
42
58
 
43
59
def find_branch(f, **args):
87
103
        if tail:
88
104
            s.insert(0, tail)
89
105
    else:
90
 
        from errors import NotBranchError
91
106
        raise NotBranchError("path %r is not within branch %r" % (rp, base))
92
107
 
93
108
    return os.sep.join(s)
101
116
    It is not necessary that f exists.
102
117
 
103
118
    Basically we keep looking up until we find the control directory or
104
 
    run into the root."""
 
119
    run into the root.  If there isn't one, raises NotBranchError.
 
120
    """
105
121
    if f == None:
106
122
        f = os.getcwd()
107
123
    elif hasattr(os.path, 'realpath'):
120
136
        head, tail = os.path.split(f)
121
137
        if head == f:
122
138
            # reached the root, whatever that may be
123
 
            raise BzrError('%r is not in a branch' % orig_f)
 
139
            raise NotBranchError('%s is not in a branch' % orig_f)
124
140
        f = head
125
 
    
 
141
 
 
142
 
 
143
 
 
144
# XXX: move into bzrlib.errors; subclass BzrError    
126
145
class DivergedBranches(Exception):
127
146
    def __init__(self, branch1, branch2):
128
147
        self.branch1 = branch1
153
172
    _lock_mode = None
154
173
    _lock_count = None
155
174
    _lock = None
 
175
    _inventory_weave = None
156
176
    
157
177
    # Map some sort of prefix into a namespace
158
178
    # stuff like "revno:10", "revid:", etc.
159
179
    # This should match a prefix with a function which accepts
160
180
    REVISION_NAMESPACES = {}
161
181
 
162
 
    def __init__(self, base, init=False, find_root=True):
 
182
    def __init__(self, base, init=False, find_root=True,
 
183
                 relax_version_check=False):
163
184
        """Create new branch object at a particular location.
164
185
 
165
186
        base -- Base directory for the branch.
171
192
        find_root -- If true and init is false, find the root of the
172
193
             existing branch containing base.
173
194
 
 
195
        relax_version_check -- If true, the usual check for the branch
 
196
            version is not applied.  This is intended only for
 
197
            upgrade/recovery type use; it's not guaranteed that
 
198
            all operations will work on old format branches.
 
199
 
174
200
        In the test suite, creation of new trees is tested using the
175
201
        `ScratchBranch` class.
176
202
        """
177
 
        from bzrlib.store import ImmutableStore
178
203
        if init:
179
204
            self.base = os.path.realpath(base)
180
205
            self._make_control()
183
208
        else:
184
209
            self.base = os.path.realpath(base)
185
210
            if not isdir(self.controlfilename('.')):
186
 
                from errors import NotBranchError
187
211
                raise NotBranchError("not a bzr branch: %s" % quotefn(base),
188
 
                                     ['use "bzr init" to initialize a new working tree',
189
 
                                      'current bzr can only operate from top-of-tree'])
190
 
        self._check_format()
 
212
                                     ['use "bzr init" to initialize a new working tree'])
 
213
        
 
214
        self._check_format(relax_version_check)
191
215
 
192
 
        self.text_store = ImmutableStore(self.controlfilename('text-store'))
 
216
        self.weave_store = WeaveStore(self.controlfilename('weaves'))
193
217
        self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
194
 
        self.inventory_store = ImmutableStore(self.controlfilename('inventory-store'))
195
218
 
196
219
 
197
220
    def __str__(self):
208
231
            self._lock.unlock()
209
232
 
210
233
 
211
 
 
212
234
    def lock_write(self):
213
235
        if self._lock_mode:
214
236
            if self._lock_mode != 'w':
224
246
            self._lock_count = 1
225
247
 
226
248
 
227
 
 
228
249
    def lock_read(self):
229
250
        if self._lock_mode:
230
251
            assert self._lock_mode in ('r', 'w'), \
237
258
            self._lock_mode = 'r'
238
259
            self._lock_count = 1
239
260
                        
240
 
 
241
 
            
242
261
    def unlock(self):
243
262
        if not self._lock_mode:
244
263
            from errors import LockError
251
270
            self._lock = None
252
271
            self._lock_mode = self._lock_count = None
253
272
 
254
 
 
255
273
    def abspath(self, name):
256
274
        """Return absolute filename for something in the branch"""
257
275
        return os.path.join(self.base, name)
258
276
 
259
 
 
260
277
    def relpath(self, path):
261
278
        """Return path relative to this branch of something inside it.
262
279
 
263
280
        Raises an error if path is not in this branch."""
264
281
        return _relpath(self.base, path)
265
282
 
266
 
 
267
283
    def controlfilename(self, file_or_path):
268
284
        """Return location relative to branch."""
269
285
        if isinstance(file_or_path, basestring):
296
312
        else:
297
313
            raise BzrError("invalid controlfile mode %r" % mode)
298
314
 
299
 
 
300
 
 
301
315
    def _make_control(self):
302
 
        from bzrlib.inventory import Inventory
303
 
        from bzrlib.xml import pack_xml
304
 
        
305
316
        os.mkdir(self.controlfilename([]))
306
317
        self.controlfile('README', 'w').write(
307
318
            "This is a Bazaar-NG control directory.\n"
308
319
            "Do not change any files in this directory.\n")
309
 
        self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT)
310
 
        for d in ('text-store', 'inventory-store', 'revision-store'):
 
320
        self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT_5)
 
321
        for d in ('text-store', 'revision-store',
 
322
                  'weaves'):
311
323
            os.mkdir(self.controlfilename(d))
312
324
        for f in ('revision-history', 'merged-patches',
313
325
                  'pending-merged-patches', 'branch-name',
316
328
            self.controlfile(f, 'w').write('')
317
329
        mutter('created control directory in ' + self.base)
318
330
 
319
 
        pack_xml(Inventory(gen_root_id()), self.controlfile('inventory','w'))
320
 
 
321
 
 
322
 
    def _check_format(self):
 
331
        # if we want per-tree root ids then this is the place to set
 
332
        # them; they're not needed for now and so ommitted for
 
333
        # simplicity.
 
334
        f = self.controlfile('inventory','w')
 
335
        bzrlib.xml5.serializer_v5.write_inventory(Inventory(), f)
 
336
        
 
337
 
 
338
 
 
339
    def _check_format(self, relax_version_check):
323
340
        """Check this branch format is supported.
324
341
 
325
 
        The current tool only supports the current unstable format.
 
342
        The format level is stored, as an integer, in
 
343
        self._branch_format for code that needs to check it later.
326
344
 
327
345
        In the future, we might need different in-memory Branch
328
346
        classes to support downlevel branches.  But not yet.
329
347
        """
330
 
        # This ignores newlines so that we can open branches created
331
 
        # on Windows from Linux and so on.  I think it might be better
332
 
        # to always make all internal files in unix format.
333
348
        fmt = self.controlfile('branch-format', 'r').read()
334
 
        fmt.replace('\r\n', '')
335
 
        if fmt != BZR_BRANCH_FORMAT:
336
 
            raise BzrError('sorry, branch format %r not supported' % fmt,
337
 
                           ['use a different bzr version',
338
 
                            'or remove the .bzr directory and "bzr init" again'])
 
349
        if fmt == BZR_BRANCH_FORMAT_5:
 
350
            self._branch_format = 5
 
351
            return
 
352
        elif relax_version_check:
 
353
            if fmt == BZR_BRANCH_FORMAT_4:
 
354
                self._branch_format = 4
 
355
                return
 
356
            
 
357
        raise BzrError('sorry, branch format "%s" not supported; ' 
 
358
                       'use a different bzr version, '
 
359
                       'or run "bzr upgrade"'
 
360
                       % fmt.rstrip('\n\r'))
 
361
        
339
362
 
340
363
    def get_root_id(self):
341
364
        """Return the id of this branches root"""
356
379
 
357
380
    def read_working_inventory(self):
358
381
        """Read the working inventory."""
359
 
        from bzrlib.inventory import Inventory
360
 
        from bzrlib.xml import unpack_xml
361
 
        from time import time
362
 
        before = time()
363
382
        self.lock_read()
364
383
        try:
365
384
            # ElementTree does its own conversion from UTF-8, so open in
366
385
            # 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
 
386
            f = self.controlfile('inventory', 'rb')
 
387
            return bzrlib.xml5.serializer_v5.read_inventory(f)
372
388
        finally:
373
389
            self.unlock()
374
390
            
380
396
        will be committed to the next revision.
381
397
        """
382
398
        from bzrlib.atomicfile import AtomicFile
383
 
        from bzrlib.xml import pack_xml
384
399
        
385
400
        self.lock_write()
386
401
        try:
387
402
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
388
403
            try:
389
 
                pack_xml(inv, f)
 
404
                bzrlib.xml5.serializer_v5.write_inventory(inv, f)
390
405
                f.commit()
391
406
            finally:
392
407
                f.close()
400
415
                         """Inventory for the working copy.""")
401
416
 
402
417
 
403
 
    def add(self, files, verbose=False, ids=None):
 
418
    def add(self, files, ids=None):
404
419
        """Make files versioned.
405
420
 
406
 
        Note that the command line normally calls smart_add instead.
 
421
        Note that the command line normally calls smart_add instead,
 
422
        which can automatically recurse.
407
423
 
408
424
        This puts the files in the Added state, so that they will be
409
425
        recorded by the next commit.
419
435
        TODO: Perhaps have an option to add the ids even if the files do
420
436
              not (yet) exist.
421
437
 
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.
 
438
        TODO: Perhaps yield the ids and paths as they're added.
428
439
        """
429
440
        # TODO: Re-adding a file that is removed in the working copy
430
441
        # should probably put it back with the previous ID.
466
477
                    file_id = gen_file_id(f)
467
478
                inv.add_path(f, kind=kind, file_id=file_id)
468
479
 
469
 
                if verbose:
470
 
                    print 'added', quotefn(f)
471
 
 
472
480
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
473
481
 
474
482
            self._write_inventory(inv)
584
592
            f.close()
585
593
 
586
594
 
587
 
    def get_revision_xml(self, revision_id):
 
595
    def has_revision(self, revision_id):
 
596
        """True if this branch has a copy of the revision.
 
597
 
 
598
        This does not necessarily imply the revision is merge
 
599
        or on the mainline."""
 
600
        return revision_id in self.revision_store
 
601
 
 
602
 
 
603
    def get_revision_xml_file(self, revision_id):
588
604
        """Return XML file object for revision object."""
589
605
        if not revision_id or not isinstance(revision_id, basestring):
590
606
            raise InvalidRevisionId(revision_id)
594
610
            try:
595
611
                return self.revision_store[revision_id]
596
612
            except IndexError:
597
 
                raise bzrlib.errors.NoSuchRevision(revision_id)
 
613
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
598
614
        finally:
599
615
            self.unlock()
600
616
 
601
617
 
 
618
    def get_revision_xml(self, revision_id):
 
619
        return self.get_revision_xml_file(revision_id).read()
 
620
 
 
621
 
602
622
    def get_revision(self, revision_id):
603
623
        """Return the Revision object for a named revision"""
604
 
        xml_file = self.get_revision_xml(revision_id)
 
624
        xml_file = self.get_revision_xml_file(revision_id)
605
625
 
606
626
        try:
607
 
            r = unpack_xml(Revision, xml_file)
 
627
            r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
608
628
        except SyntaxError, e:
609
629
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
610
630
                                         [revision_id,
639
659
 
640
660
    def get_revision_sha1(self, revision_id):
641
661
        """Hash the stored value of a revision, and return it."""
642
 
        # In the future, revision entries will be signed. At that
643
 
        # point, it is probably best *not* to include the signature
644
 
        # in the revision hash. Because that lets you re-sign
645
 
        # the revision, (add signatures/remove signatures) and still
646
 
        # have all hash pointers stay consistent.
647
 
        # But for now, just hash the contents.
648
 
        return bzrlib.osutils.sha_file(self.get_revision_xml(revision_id))
649
 
 
650
 
 
651
 
    def get_inventory(self, inventory_id):
652
 
        """Get Inventory object by hash.
653
 
 
654
 
        TODO: Perhaps for this and similar methods, take a revision
655
 
               parameter which can be either an integer revno or a
656
 
               string hash."""
657
 
        from bzrlib.inventory import Inventory
658
 
        from bzrlib.xml import unpack_xml
659
 
 
660
 
        return unpack_xml(Inventory, self.inventory_store[inventory_id])
661
 
            
662
 
 
663
 
    def get_inventory_sha1(self, inventory_id):
 
662
        return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
 
663
 
 
664
 
 
665
    def get_ancestry(self, revision_id):
 
666
        """Return a list of revision-ids integrated by a revision.
 
667
        """
 
668
        w = self.weave_store.get_weave(ANCESTRY_FILEID)
 
669
        # strip newlines
 
670
        return [l[:-1] for l in w.get_iter(w.lookup(revision_id))]
 
671
 
 
672
 
 
673
    def get_inventory_weave(self):
 
674
        return self.weave_store.get_weave(INVENTORY_FILEID)
 
675
 
 
676
 
 
677
    def get_inventory(self, revision_id):
 
678
        """Get Inventory object by hash."""
 
679
        # FIXME: The text gets passed around a lot coming from the weave.
 
680
        f = StringIO(self.get_inventory_xml(revision_id))
 
681
        return bzrlib.xml5.serializer_v5.read_inventory(f)
 
682
 
 
683
 
 
684
    def get_inventory_xml(self, revision_id):
 
685
        """Get inventory XML as a file object."""
 
686
        try:
 
687
            assert isinstance(revision_id, basestring), type(revision_id)
 
688
            iw = self.get_inventory_weave()
 
689
            return iw.get_text(iw.lookup(revision_id))
 
690
        except IndexError:
 
691
            raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
 
692
 
 
693
 
 
694
    def get_inventory_sha1(self, revision_id):
664
695
        """Return the sha1 hash of the inventory entry
665
696
        """
666
 
        return sha_file(self.inventory_store[inventory_id])
 
697
        return self.get_revision(revision_id).inventory_sha1
667
698
 
668
699
 
669
700
    def get_revision_inventory(self, revision_id):
670
701
        """Return inventory of a past revision."""
671
 
        # bzr 0.0.6 imposes the constraint that the inventory_id
 
702
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
672
703
        # must be the same as its revision, so this is trivial.
673
704
        if revision_id == None:
674
 
            from bzrlib.inventory import Inventory
675
705
            return Inventory(self.get_root_id())
676
706
        else:
677
707
            return self.get_inventory(revision_id)
697
727
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
698
728
        >>> sb.common_ancestor(sb) == (None, None)
699
729
        True
700
 
        >>> commit.commit(sb, "Committing first revision", verbose=False)
 
730
        >>> commit.commit(sb, "Committing first revision")
701
731
        >>> sb.common_ancestor(sb)[0]
702
732
        1
703
733
        >>> clone = sb.clone()
704
 
        >>> commit.commit(sb, "Committing second revision", verbose=False)
 
734
        >>> commit.commit(sb, "Committing second revision")
705
735
        >>> sb.common_ancestor(sb)[0]
706
736
        2
707
737
        >>> sb.common_ancestor(clone)[0]
708
738
        1
709
 
        >>> commit.commit(clone, "Committing divergent second revision", 
710
 
        ...               verbose=False)
 
739
        >>> commit.commit(clone, "Committing divergent second revision")
711
740
        >>> sb.common_ancestor(clone)[0]
712
741
        1
713
742
        >>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
745
774
        return len(self.revision_history())
746
775
 
747
776
 
748
 
    def last_patch(self):
 
777
    def last_revision(self):
749
778
        """Return last patch hash, or None if no history.
750
779
        """
751
780
        ph = self.revision_history()
755
784
            return None
756
785
 
757
786
 
758
 
    def missing_revisions(self, other, stop_revision=None):
759
 
        """
 
787
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
 
788
        """Return a list of new revisions that would perfectly fit.
 
789
        
760
790
        If self and other have not diverged, return a list of the revisions
761
791
        present in other, but missing from self.
762
792
 
782
812
        Traceback (most recent call last):
783
813
        DivergedBranches: These branches have diverged.
784
814
        """
 
815
        # FIXME: If the branches have diverged, but the latest
 
816
        # revision in this branch is completely merged into the other,
 
817
        # then we should still be able to pull.
785
818
        self_history = self.revision_history()
786
819
        self_len = len(self_history)
787
820
        other_history = other.revision_history()
793
826
 
794
827
        if stop_revision is None:
795
828
            stop_revision = other_len
796
 
        elif stop_revision > other_len:
797
 
            raise NoSuchRevision(self, stop_revision)
 
829
        else:
 
830
            assert isinstance(stop_revision, int)
 
831
            if stop_revision > other_len:
 
832
                raise bzrlib.errors.NoSuchRevision(self, stop_revision)
798
833
        
799
834
        return other_history[self_len:stop_revision]
800
835
 
801
836
 
802
 
    def update_revisions(self, other, stop_revision=None):
803
 
        """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
 
837
    def update_revisions(self, other, stop_revno=None):
 
838
        """Pull in new perfect-fit revisions.
824
839
        """
825
 
        from bzrlib.progress import ProgressBar
826
 
 
827
 
        pb = ProgressBar()
828
 
 
829
 
        pb.update('comparing histories')
830
 
        revision_ids = self.missing_revisions(other, stop_revision)
831
 
 
832
 
        if hasattr(other.revision_store, "prefetch"):
833
 
            other.revision_store.prefetch(revision_ids)
834
 
        if hasattr(other.inventory_store, "prefetch"):
835
 
            inventory_ids = [other.get_revision(r).inventory_id
836
 
                             for r in revision_ids]
837
 
            other.inventory_store.prefetch(inventory_ids)
838
 
                
839
 
        revisions = []
840
 
        needed_texts = set()
841
 
        i = 0
842
 
        for rev_id in revision_ids:
843
 
            i += 1
844
 
            pb.update('fetching revision', i, len(revision_ids))
845
 
            rev = other.get_revision(rev_id)
846
 
            revisions.append(rev)
847
 
            inv = other.get_inventory(str(rev.inventory_id))
848
 
            for key, entry in inv.iter_entries():
849
 
                if entry.text_id is None:
850
 
                    continue
851
 
                if entry.text_id not in self.text_store:
852
 
                    needed_texts.add(entry.text_id)
853
 
 
854
 
        pb.clear()
855
 
                    
856
 
        count = self.text_store.copy_multi(other.text_store, needed_texts)
857
 
        print "Added %d texts." % count 
858
 
        inventory_ids = [ f.inventory_id for f in revisions ]
859
 
        count = self.inventory_store.copy_multi(other.inventory_store, 
860
 
                                                inventory_ids)
861
 
        print "Added %d inventories." % count 
862
 
        revision_ids = [ f.revision_id for f in revisions]
863
 
        count = self.revision_store.copy_multi(other.revision_store, 
864
 
                                               revision_ids)
865
 
        for revision_id in revision_ids:
866
 
            self.append_revision(revision_id)
867
 
        print "Added %d revisions." % count
868
 
                    
869
 
        
 
840
        from bzrlib.fetch import greedy_fetch
 
841
 
 
842
        if stop_revno:
 
843
            stop_revision = other.lookup_revision(stop_revno)
 
844
        else:
 
845
            stop_revision = None
 
846
        greedy_fetch(to_branch=self, from_branch=other,
 
847
                     revision=stop_revision)
 
848
 
 
849
        pullable_revs = self.missing_revisions(other, stop_revision)
 
850
 
 
851
        if pullable_revs:
 
852
            greedy_fetch(to_branch=self,
 
853
                         from_branch=other,
 
854
                         revision=pullable_revs[-1])
 
855
            self.append_revision(*pullable_revs)
 
856
 
 
857
 
870
858
    def commit(self, *args, **kw):
871
 
        from bzrlib.commit import commit
872
 
        commit(self, *args, **kw)
 
859
        from bzrlib.commit import Commit
 
860
        Commit().commit(self, *args, **kw)
873
861
        
874
862
 
875
863
    def lookup_revision(self, revision):
876
864
        """Return the revision identifier for a given revision information."""
877
 
        revno, info = self.get_revision_info(revision)
 
865
        revno, info = self._get_revision_info(revision)
878
866
        return info
879
867
 
 
868
 
 
869
    def revision_id_to_revno(self, revision_id):
 
870
        """Given a revision id, return its revno"""
 
871
        history = self.revision_history()
 
872
        try:
 
873
            return history.index(revision_id) + 1
 
874
        except ValueError:
 
875
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
876
 
 
877
 
880
878
    def get_revision_info(self, revision):
881
879
        """Return (revno, revision id) for revision identifier.
882
880
 
885
883
        revision can also be a string, in which case it is parsed for something like
886
884
            'date:' or 'revid:' etc.
887
885
        """
 
886
        revno, rev_id = self._get_revision_info(revision)
 
887
        if revno is None:
 
888
            raise bzrlib.errors.NoSuchRevision(self, revision)
 
889
        return revno, rev_id
 
890
 
 
891
    def get_rev_id(self, revno, history=None):
 
892
        """Find the revision id of the specified revno."""
 
893
        if revno == 0:
 
894
            return None
 
895
        if history is None:
 
896
            history = self.revision_history()
 
897
        elif revno <= 0 or revno > len(history):
 
898
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
899
        return history[revno - 1]
 
900
 
 
901
    def _get_revision_info(self, revision):
 
902
        """Return (revno, revision id) for revision specifier.
 
903
 
 
904
        revision can be an integer, in which case it is assumed to be revno
 
905
        (though this will translate negative values into positive ones)
 
906
        revision can also be a string, in which case it is parsed for something
 
907
        like 'date:' or 'revid:' etc.
 
908
 
 
909
        A revid is always returned.  If it is None, the specifier referred to
 
910
        the null revision.  If the revid does not occur in the revision
 
911
        history, revno will be None.
 
912
        """
 
913
        
888
914
        if revision is None:
889
915
            return 0, None
890
916
        revno = None
894
920
            pass
895
921
        revs = self.revision_history()
896
922
        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
923
            if revision < 0:
901
924
                revno = len(revs) + revision + 1
902
925
            else:
903
926
                revno = revision
 
927
            rev_id = self.get_rev_id(revno, revs)
904
928
        elif isinstance(revision, basestring):
905
929
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
906
930
                if revision.startswith(prefix):
907
 
                    revno = func(self, revs, revision)
 
931
                    result = func(self, revs, revision)
 
932
                    if len(result) > 1:
 
933
                        revno, rev_id = result
 
934
                    else:
 
935
                        revno = result[0]
 
936
                        rev_id = self.get_rev_id(revno, revs)
908
937
                    break
909
938
            else:
910
 
                raise BzrError('No namespace registered for string: %r' % revision)
 
939
                raise BzrError('No namespace registered for string: %r' %
 
940
                               revision)
 
941
        else:
 
942
            raise TypeError('Unhandled revision type %s' % revision)
911
943
 
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]
 
944
        if revno is None:
 
945
            if rev_id is None:
 
946
                raise bzrlib.errors.NoSuchRevision(self, revision)
 
947
        return revno, rev_id
915
948
 
916
949
    def _namespace_revno(self, revs, revision):
917
950
        """Lookup a revision by revision number"""
918
951
        assert revision.startswith('revno:')
919
952
        try:
920
 
            return int(revision[6:])
 
953
            return (int(revision[6:]),)
921
954
        except ValueError:
922
955
            return None
923
956
    REVISION_NAMESPACES['revno:'] = _namespace_revno
924
957
 
925
958
    def _namespace_revid(self, revs, revision):
926
959
        assert revision.startswith('revid:')
 
960
        rev_id = revision[len('revid:'):]
927
961
        try:
928
 
            return revs.index(revision[6:]) + 1
 
962
            return revs.index(rev_id) + 1, rev_id
929
963
        except ValueError:
930
 
            return None
 
964
            return None, rev_id
931
965
    REVISION_NAMESPACES['revid:'] = _namespace_revid
932
966
 
933
967
    def _namespace_last(self, revs, revision):
935
969
        try:
936
970
            offset = int(revision[5:])
937
971
        except ValueError:
938
 
            return None
 
972
            return (None,)
939
973
        else:
940
974
            if offset <= 0:
941
975
                raise BzrError('You must supply a positive value for --revision last:XXX')
942
 
            return len(revs) - offset + 1
 
976
            return (len(revs) - offset + 1,)
943
977
    REVISION_NAMESPACES['last:'] = _namespace_last
944
978
 
945
979
    def _namespace_tag(self, revs, revision):
1020
1054
                # TODO: Handle timezone.
1021
1055
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1022
1056
                if first >= dt and (last is None or dt >= last):
1023
 
                    return i+1
 
1057
                    return (i+1,)
1024
1058
        else:
1025
1059
            for i in range(len(revs)):
1026
1060
                r = self.get_revision(revs[i])
1027
1061
                # TODO: Handle timezone.
1028
1062
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1029
1063
                if first <= dt and (last is None or dt <= last):
1030
 
                    return i+1
 
1064
                    return (i+1,)
1031
1065
    REVISION_NAMESPACES['date:'] = _namespace_date
1032
1066
 
1033
1067
    def revision_tree(self, revision_id):
1041
1075
            return EmptyTree()
1042
1076
        else:
1043
1077
            inv = self.get_revision_inventory(revision_id)
1044
 
            return RevisionTree(self.text_store, inv)
 
1078
            return RevisionTree(self.weave_store, inv, revision_id)
1045
1079
 
1046
1080
 
1047
1081
    def working_tree(self):
1055
1089
 
1056
1090
        If there are no revisions yet, return an `EmptyTree`.
1057
1091
        """
1058
 
        r = self.last_patch()
1059
 
        if r == None:
1060
 
            return EmptyTree()
1061
 
        else:
1062
 
            return RevisionTree(self.text_store, self.get_revision_inventory(r))
1063
 
 
 
1092
        return self.revision_tree(self.last_revision())
1064
1093
 
1065
1094
 
1066
1095
    def rename_one(self, from_rel, to_rel):
1098
1127
 
1099
1128
            inv.rename(file_id, to_dir_id, to_tail)
1100
1129
 
1101
 
            print "%s => %s" % (from_rel, to_rel)
1102
 
 
1103
1130
            from_abs = self.abspath(from_rel)
1104
1131
            to_abs = self.abspath(to_rel)
1105
1132
            try:
1124
1151
 
1125
1152
        Note that to_name is only the last component of the new name;
1126
1153
        this doesn't change the directory.
 
1154
 
 
1155
        This returns a list of (from_path, to_path) pairs for each
 
1156
        entry that is moved.
1127
1157
        """
 
1158
        result = []
1128
1159
        self.lock_write()
1129
1160
        try:
1130
1161
            ## TODO: Option to move IDs only
1165
1196
            for f in from_paths:
1166
1197
                name_tail = splitpath(f)[-1]
1167
1198
                dest_path = appendpath(to_name, name_tail)
1168
 
                print "%s => %s" % (f, dest_path)
 
1199
                result.append((f, dest_path))
1169
1200
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1170
1201
                try:
1171
1202
                    os.rename(self.abspath(f), self.abspath(dest_path))
1177
1208
        finally:
1178
1209
            self.unlock()
1179
1210
 
 
1211
        return result
 
1212
 
1180
1213
 
1181
1214
    def revert(self, filenames, old_tree=None, backups=True):
1182
1215
        """Restore selected files to the versions from a previous tree.
1238
1271
 
1239
1272
 
1240
1273
    def add_pending_merge(self, revision_id):
1241
 
        from bzrlib.revision import validate_revision_id
1242
 
 
1243
1274
        validate_revision_id(revision_id)
1244
 
 
 
1275
        # TODO: Perhaps should check at this point that the
 
1276
        # history of the revision is actually present?
1245
1277
        p = self.pending_merges()
1246
1278
        if revision_id in p:
1247
1279
            return
1264
1296
            self.unlock()
1265
1297
 
1266
1298
 
 
1299
    def get_parent(self):
 
1300
        """Return the parent location of the branch.
 
1301
 
 
1302
        This is the default location for push/pull/missing.  The usual
 
1303
        pattern is that the user can override it by specifying a
 
1304
        location.
 
1305
        """
 
1306
        import errno
 
1307
        _locs = ['parent', 'pull', 'x-pull']
 
1308
        for l in _locs:
 
1309
            try:
 
1310
                return self.controlfile(l, 'r').read().strip('\n')
 
1311
            except IOError, e:
 
1312
                if e.errno != errno.ENOENT:
 
1313
                    raise
 
1314
        return None
 
1315
 
 
1316
 
 
1317
    def set_parent(self, url):
 
1318
        # TODO: Maybe delete old location files?
 
1319
        from bzrlib.atomicfile import AtomicFile
 
1320
        self.lock_write()
 
1321
        try:
 
1322
            f = AtomicFile(self.controlfilename('parent'))
 
1323
            try:
 
1324
                f.write(url + '\n')
 
1325
                f.commit()
 
1326
            finally:
 
1327
                f.close()
 
1328
        finally:
 
1329
            self.unlock()
 
1330
 
 
1331
    def check_revno(self, revno):
 
1332
        """\
 
1333
        Check whether a revno corresponds to any revision.
 
1334
        Zero (the NULL revision) is considered valid.
 
1335
        """
 
1336
        if revno != 0:
 
1337
            self.check_real_revno(revno)
 
1338
            
 
1339
    def check_real_revno(self, revno):
 
1340
        """\
 
1341
        Check whether a revno corresponds to a real revision.
 
1342
        Zero (the NULL revision) is considered invalid
 
1343
        """
 
1344
        if revno < 1 or revno > self.revno():
 
1345
            raise InvalidRevisionNumber(revno)
 
1346
        
 
1347
        
 
1348
 
1267
1349
 
1268
1350
class ScratchBranch(Branch):
1269
1351
    """Special test class: a branch that cleans up after itself.
1311
1393
        os.rmdir(base)
1312
1394
        copytree(self.base, base, symlinks=True)
1313
1395
        return ScratchBranch(base=base)
 
1396
 
 
1397
 
1314
1398
        
1315
1399
    def __del__(self):
1316
1400
        self.destroy()
1386
1470
    """Return a new tree-root file id."""
1387
1471
    return gen_file_id('TREE_ROOT')
1388
1472
 
 
1473
 
 
1474
def pull_loc(branch):
 
1475
    # TODO: Should perhaps just make attribute be 'base' in
 
1476
    # RemoteBranch and Branch?
 
1477
    if hasattr(branch, "baseurl"):
 
1478
        return branch.baseurl
 
1479
    else:
 
1480
        return branch.base
 
1481
 
 
1482
 
 
1483
def copy_branch(branch_from, to_location, revision=None):
 
1484
    """Copy branch_from into the existing directory to_location.
 
1485
 
 
1486
    revision
 
1487
        If not None, only revisions up to this point will be copied.
 
1488
        The head of the new branch will be that revision.  Can be a
 
1489
        revno or revid.
 
1490
 
 
1491
    to_location
 
1492
        The name of a local directory that exists but is empty.
 
1493
    """
 
1494
    # TODO: This could be done *much* more efficiently by just copying
 
1495
    # all the whole weaves and revisions, rather than getting one
 
1496
    # revision at a time.
 
1497
    from bzrlib.merge import merge
 
1498
    from bzrlib.branch import Branch
 
1499
 
 
1500
    assert isinstance(branch_from, Branch)
 
1501
    assert isinstance(to_location, basestring)
 
1502
    
 
1503
    br_to = Branch(to_location, init=True)
 
1504
    br_to.set_root_id(branch_from.get_root_id())
 
1505
    if revision is None:
 
1506
        revno = None
 
1507
    else:
 
1508
        revno, rev_id = branch_from.get_revision_info(revision)
 
1509
    br_to.update_revisions(branch_from, stop_revno=revno)
 
1510
    merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
1511
          check_clean=False, ignore_zero=True)
 
1512
    
 
1513
    from_location = pull_loc(branch_from)
 
1514
    br_to.set_parent(pull_loc(branch_from))
 
1515