~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2005-07-07 02:07:03 UTC
  • Revision ID: mbp@sourcefrog.net-20050707020702-0e24e478b738d4db
- Put files inside an exported tarball into a top-level directory rather than 
  dumping them into the current directory.  

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
######################################################################
157
150
    _lock_count = None
158
151
    _lock = None
159
152
    
160
 
    # Map some sort of prefix into a namespace
161
 
    # stuff like "revno:10", "revid:", etc.
162
 
    # This should match a prefix with a function which accepts
163
 
    REVISION_NAMESPACES = {}
164
 
 
165
153
    def __init__(self, base, init=False, find_root=True):
166
154
        """Create new branch object at a particular location.
167
155
 
168
 
        base -- Base directory for the branch. May be a file:// url.
 
156
        base -- Base directory for the branch.
169
157
        
170
158
        init -- If True, create new control files in a previously
171
159
             unversioned directory.  If False, the branch must already
184
172
        elif find_root:
185
173
            self.base = find_branch_root(base)
186
174
        else:
187
 
            if base.startswith("file://"):
188
 
                base = base[7:]
189
175
            self.base = os.path.realpath(base)
190
176
            if not isdir(self.controlfilename('.')):
 
177
                from errors import NotBranchError
191
178
                raise NotBranchError("not a bzr branch: %s" % quotefn(base),
192
179
                                     ['use "bzr init" to initialize a new working tree',
193
180
                                      'current bzr can only operate from top-of-tree'])
207
194
 
208
195
    def __del__(self):
209
196
        if self._lock_mode or self._lock:
210
 
            from bzrlib.warnings import warn
 
197
            from warnings import warn
211
198
            warn("branch %r was not explicitly unlocked" % self)
212
199
            self._lock.unlock()
213
200
 
 
201
 
 
202
 
214
203
    def lock_write(self):
215
204
        if self._lock_mode:
216
205
            if self._lock_mode != 'w':
217
 
                from bzrlib.errors import LockError
 
206
                from errors import LockError
218
207
                raise LockError("can't upgrade to a write lock from %r" %
219
208
                                self._lock_mode)
220
209
            self._lock_count += 1
226
215
            self._lock_count = 1
227
216
 
228
217
 
 
218
 
229
219
    def lock_read(self):
230
220
        if self._lock_mode:
231
221
            assert self._lock_mode in ('r', 'w'), \
238
228
            self._lock_mode = 'r'
239
229
            self._lock_count = 1
240
230
                        
 
231
 
 
232
            
241
233
    def unlock(self):
242
234
        if not self._lock_mode:
243
 
            from bzrlib.errors import LockError
 
235
            from errors import LockError
244
236
            raise LockError('branch %r is not locked' % (self))
245
237
 
246
238
        if self._lock_count > 1:
250
242
            self._lock = None
251
243
            self._lock_mode = self._lock_count = None
252
244
 
 
245
 
253
246
    def abspath(self, name):
254
247
        """Return absolute filename for something in the branch"""
255
248
        return os.path.join(self.base, name)
256
249
 
 
250
 
257
251
    def relpath(self, path):
258
252
        """Return path relative to this branch of something inside it.
259
253
 
260
254
        Raises an error if path is not in this branch."""
261
255
        return _relpath(self.base, path)
262
256
 
 
257
 
263
258
    def controlfilename(self, file_or_path):
264
259
        """Return location relative to branch."""
265
260
        if isinstance(file_or_path, basestring):
292
287
        else:
293
288
            raise BzrError("invalid controlfile mode %r" % mode)
294
289
 
 
290
 
 
291
 
295
292
    def _make_control(self):
296
293
        from bzrlib.inventory import Inventory
 
294
        from bzrlib.xml import pack_xml
297
295
        
298
296
        os.mkdir(self.controlfilename([]))
299
297
        self.controlfile('README', 'w').write(
309
307
            self.controlfile(f, 'w').write('')
310
308
        mutter('created control directory in ' + self.base)
311
309
 
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)
 
310
        pack_xml(Inventory(), self.controlfile('inventory','w'))
317
311
 
318
312
 
319
313
    def _check_format(self):
328
322
        # on Windows from Linux and so on.  I think it might be better
329
323
        # to always make all internal files in unix format.
330
324
        fmt = self.controlfile('branch-format', 'r').read()
331
 
        fmt = fmt.replace('\r\n', '\n')
 
325
        fmt.replace('\r\n', '')
332
326
        if fmt != BZR_BRANCH_FORMAT:
333
327
            raise BzrError('sorry, branch format %r not supported' % fmt,
334
328
                           ['use a different bzr version',
335
329
                            'or remove the .bzr directory and "bzr init" again'])
336
330
 
337
 
    def get_root_id(self):
338
 
        """Return the id of this branches root"""
339
 
        inv = self.read_working_inventory()
340
 
        return inv.root.file_id
341
331
 
342
 
    def set_root_id(self, file_id):
343
 
        inv = self.read_working_inventory()
344
 
        orig_root_id = inv.root.file_id
345
 
        del inv._byid[inv.root.file_id]
346
 
        inv.root.file_id = file_id
347
 
        inv._byid[inv.root.file_id] = inv.root
348
 
        for fid in inv:
349
 
            entry = inv[fid]
350
 
            if entry.parent_id in (None, orig_root_id):
351
 
                entry.parent_id = inv.root.file_id
352
 
        self._write_inventory(inv)
353
332
 
354
333
    def read_working_inventory(self):
355
334
        """Read the working inventory."""
356
335
        from bzrlib.inventory import Inventory
 
336
        from bzrlib.xml import unpack_xml
 
337
        from time import time
 
338
        before = time()
357
339
        self.lock_read()
358
340
        try:
359
341
            # ElementTree does its own conversion from UTF-8, so open in
360
342
            # binary.
361
 
            f = self.controlfile('inventory', 'rb')
362
 
            return bzrlib.xml.serializer_v4.read_inventory(f)
 
343
            inv = unpack_xml(Inventory,
 
344
                                  self.controlfile('inventory', 'rb'))
 
345
            mutter("loaded inventory of %d items in %f"
 
346
                   % (len(inv), time() - before))
 
347
            return inv
363
348
        finally:
364
349
            self.unlock()
365
350
            
371
356
        will be committed to the next revision.
372
357
        """
373
358
        from bzrlib.atomicfile import AtomicFile
 
359
        from bzrlib.xml import pack_xml
374
360
        
375
361
        self.lock_write()
376
362
        try:
377
363
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
378
364
            try:
379
 
                bzrlib.xml.serializer_v4.write_inventory(inv, f)
 
365
                pack_xml(inv, f)
380
366
                f.commit()
381
367
            finally:
382
368
                f.close()
390
376
                         """Inventory for the working copy.""")
391
377
 
392
378
 
393
 
    def add(self, files, ids=None):
 
379
    def add(self, files, verbose=False, ids=None):
394
380
        """Make files versioned.
395
381
 
396
 
        Note that the command line normally calls smart_add instead,
397
 
        which can automatically recurse.
 
382
        Note that the command line normally calls smart_add instead.
398
383
 
399
384
        This puts the files in the Added state, so that they will be
400
385
        recorded by the next commit.
410
395
        TODO: Perhaps have an option to add the ids even if the files do
411
396
              not (yet) exist.
412
397
 
413
 
        TODO: Perhaps yield the ids and paths as they're added.
 
398
        TODO: Perhaps return the ids of the files?  But then again it
 
399
              is easy to retrieve them if they're needed.
 
400
 
 
401
        TODO: Adding a directory should optionally recurse down and
 
402
              add all non-ignored children.  Perhaps do that in a
 
403
              higher-level method.
414
404
        """
 
405
        from bzrlib.textui import show_status
415
406
        # TODO: Re-adding a file that is removed in the working copy
416
407
        # should probably put it back with the previous ID.
417
408
        if isinstance(files, basestring):
452
443
                    file_id = gen_file_id(f)
453
444
                inv.add_path(f, kind=kind, file_id=file_id)
454
445
 
 
446
                if verbose:
 
447
                    print 'added', quotefn(f)
 
448
 
455
449
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
456
450
 
457
451
            self._write_inventory(inv)
467
461
            # use inventory as it was in that revision
468
462
            file_id = tree.inventory.path2id(file)
469
463
            if not file_id:
470
 
                raise BzrError("%r is not present in revision %s" % (file, revno))
 
464
                raise BzrError("%r is not present in revision %d" % (file, revno))
471
465
            tree.print_file(file_id)
472
466
        finally:
473
467
            self.unlock()
487
481
        is the opposite of add.  Removing it is consistent with most
488
482
        other tools.  Maybe an option.
489
483
        """
 
484
        from bzrlib.textui import show_status
490
485
        ## TODO: Normalize names
491
486
        ## TODO: Remove nested loops; better scalability
492
487
        if isinstance(files, basestring):
521
516
    # FIXME: this doesn't need to be a branch method
522
517
    def set_inventory(self, new_inventory_list):
523
518
        from bzrlib.inventory import Inventory, InventoryEntry
524
 
        inv = Inventory(self.get_root_id())
 
519
        inv = Inventory()
525
520
        for path, file_id, parent, kind in new_inventory_list:
526
521
            name = os.path.basename(path)
527
522
            if name == "":
549
544
        return self.working_tree().unknowns()
550
545
 
551
546
 
552
 
    def append_revision(self, *revision_ids):
 
547
    def append_revision(self, revision_id):
553
548
        from bzrlib.atomicfile import AtomicFile
554
549
 
555
 
        for revision_id in revision_ids:
556
 
            mutter("add {%s} to revision-history" % revision_id)
557
 
 
558
 
        rev_history = self.revision_history()
559
 
        rev_history.extend(revision_ids)
 
550
        mutter("add {%s} to revision-history" % revision_id)
 
551
        rev_history = self.revision_history() + [revision_id]
560
552
 
561
553
        f = AtomicFile(self.controlfilename('revision-history'))
562
554
        try:
567
559
            f.close()
568
560
 
569
561
 
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
562
    def get_revision(self, revision_id):
590
563
        """Return the Revision object for a named revision"""
591
 
        xml_file = self.get_revision_xml_file(revision_id)
 
564
        from bzrlib.revision import Revision
 
565
        from bzrlib.xml import unpack_xml
592
566
 
 
567
        self.lock_read()
593
568
        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)])
 
569
            if not revision_id or not isinstance(revision_id, basestring):
 
570
                raise ValueError('invalid revision-id: %r' % revision_id)
 
571
            r = unpack_xml(Revision, self.revision_store[revision_id])
 
572
        finally:
 
573
            self.unlock()
599
574
            
600
575
        assert r.revision_id == revision_id
601
576
        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
577
        
626
578
 
627
579
    def get_revision_sha1(self, revision_id):
632
584
        # the revision, (add signatures/remove signatures) and still
633
585
        # have all hash pointers stay consistent.
634
586
        # But for now, just hash the contents.
635
 
        return bzrlib.osutils.sha_file(self.get_revision_xml(revision_id))
 
587
        return sha_file(self.revision_store[revision_id])
636
588
 
637
589
 
638
590
    def get_inventory(self, inventory_id):
642
594
               parameter which can be either an integer revno or a
643
595
               string hash."""
644
596
        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
 
597
        from bzrlib.xml import unpack_xml
 
598
 
 
599
        return unpack_xml(Inventory, self.inventory_store[inventory_id])
655
600
            
656
601
 
657
602
    def get_inventory_sha1(self, inventory_id):
658
603
        """Return the sha1 hash of the inventory entry
659
604
        """
660
 
        return sha_file(self.get_inventory_xml(inventory_id))
 
605
        return sha_file(self.inventory_store[inventory_id])
661
606
 
662
607
 
663
608
    def get_revision_inventory(self, revision_id):
666
611
        # must be the same as its revision, so this is trivial.
667
612
        if revision_id == None:
668
613
            from bzrlib.inventory import Inventory
669
 
            return Inventory(self.get_root_id())
 
614
            return Inventory()
670
615
        else:
671
616
            return self.get_inventory(revision_id)
672
617
 
687
632
 
688
633
    def common_ancestor(self, other, self_revno=None, other_revno=None):
689
634
        """
690
 
        >>> from bzrlib.commit import commit
 
635
        >>> import commit
691
636
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
692
637
        >>> sb.common_ancestor(sb) == (None, None)
693
638
        True
694
 
        >>> commit(sb, "Committing first revision", verbose=False)
 
639
        >>> commit.commit(sb, "Committing first revision", verbose=False)
695
640
        >>> sb.common_ancestor(sb)[0]
696
641
        1
697
642
        >>> clone = sb.clone()
698
 
        >>> commit(sb, "Committing second revision", verbose=False)
 
643
        >>> commit.commit(sb, "Committing second revision", verbose=False)
699
644
        >>> sb.common_ancestor(sb)[0]
700
645
        2
701
646
        >>> sb.common_ancestor(clone)[0]
702
647
        1
703
 
        >>> commit(clone, "Committing divergent second revision", 
 
648
        >>> commit.commit(clone, "Committing divergent second revision", 
704
649
        ...               verbose=False)
705
650
        >>> sb.common_ancestor(clone)[0]
706
651
        1
729
674
                return r+1, my_history[r]
730
675
        return None, None
731
676
 
 
677
    def enum_history(self, direction):
 
678
        """Return (revno, revision_id) for history of branch.
 
679
 
 
680
        direction
 
681
            'forward' is from earliest to latest
 
682
            'reverse' is from latest to earliest
 
683
        """
 
684
        rh = self.revision_history()
 
685
        if direction == 'forward':
 
686
            i = 1
 
687
            for rid in rh:
 
688
                yield i, rid
 
689
                i += 1
 
690
        elif direction == 'reverse':
 
691
            i = len(rh)
 
692
            while i > 0:
 
693
                yield i, rh[i-1]
 
694
                i -= 1
 
695
        else:
 
696
            raise ValueError('invalid history direction', direction)
 
697
 
732
698
 
733
699
    def revno(self):
734
700
        """Return current revision number for this branch.
749
715
            return None
750
716
 
751
717
 
752
 
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
 
718
    def missing_revisions(self, other, stop_revision=None):
753
719
        """
754
720
        If self and other have not diverged, return a list of the revisions
755
721
        present in other, but missing from self.
788
754
        if stop_revision is None:
789
755
            stop_revision = other_len
790
756
        elif stop_revision > other_len:
791
 
            raise bzrlib.errors.NoSuchRevision(self, stop_revision)
 
757
            raise NoSuchRevision(self, stop_revision)
792
758
        
793
759
        return other_history[self_len:stop_revision]
794
760
 
795
761
 
796
762
    def update_revisions(self, other, stop_revision=None):
797
763
        """Pull in all new revisions from other branch.
 
764
        
 
765
        >>> from bzrlib.commit import commit
 
766
        >>> bzrlib.trace.silent = True
 
767
        >>> br1 = ScratchBranch(files=['foo', 'bar'])
 
768
        >>> br1.add('foo')
 
769
        >>> br1.add('bar')
 
770
        >>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
 
771
        >>> br2 = ScratchBranch()
 
772
        >>> br2.update_revisions(br1)
 
773
        Added 2 texts.
 
774
        Added 1 inventories.
 
775
        Added 1 revisions.
 
776
        >>> br2.revision_history()
 
777
        [u'REVISION-ID-1']
 
778
        >>> br2.update_revisions(br1)
 
779
        Added 0 texts.
 
780
        Added 0 inventories.
 
781
        Added 0 revisions.
 
782
        >>> br1.text_store.total_size() == br2.text_store.total_size()
 
783
        True
798
784
        """
799
 
        from bzrlib.fetch import greedy_fetch
800
 
        from bzrlib.revision import get_intervening_revisions
801
 
 
802
 
        pb = bzrlib.ui.ui_factory.progress_bar()
 
785
        from bzrlib.progress import ProgressBar
 
786
        try:
 
787
            set
 
788
        except NameError:
 
789
            from sets import Set as set
 
790
 
 
791
        pb = ProgressBar()
 
792
 
803
793
        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):
 
794
        revision_ids = self.missing_revisions(other, stop_revision)
 
795
 
823
796
        if hasattr(other.revision_store, "prefetch"):
824
797
            other.revision_store.prefetch(revision_ids)
825
798
        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
 
799
            inventory_ids = [other.get_revision(r).inventory_id
 
800
                             for r in revision_ids]
833
801
            other.inventory_store.prefetch(inventory_ids)
834
 
 
835
 
        if pb is None:
836
 
            pb = bzrlib.ui.ui_factory.progress_bar()
837
802
                
838
803
        revisions = []
839
804
        needed_texts = set()
840
805
        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
 
 
 
806
        for rev_id in revision_ids:
 
807
            i += 1
 
808
            pb.update('fetching revision', i, len(revision_ids))
 
809
            rev = other.get_revision(rev_id)
851
810
            revisions.append(rev)
852
811
            inv = other.get_inventory(str(rev.inventory_id))
853
812
            for key, entry in inv.iter_entries():
858
817
 
859
818
        pb.clear()
860
819
                    
861
 
        count, cp_fail = self.text_store.copy_multi(other.text_store, 
862
 
                                                    needed_texts)
863
 
        #print "Added %d texts." % count 
 
820
        count = self.text_store.copy_multi(other.text_store, needed_texts)
 
821
        print "Added %d texts." % count 
864
822
        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 
 
823
        count = self.inventory_store.copy_multi(other.inventory_store, 
 
824
                                                inventory_ids)
 
825
        print "Added %d inventories." % count 
868
826
        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
 
 
 
827
        count = self.revision_store.copy_multi(other.revision_store, 
 
828
                                               revision_ids)
 
829
        for revision_id in revision_ids:
 
830
            self.append_revision(revision_id)
 
831
        print "Added %d revisions." % count
 
832
                    
 
833
        
877
834
    def commit(self, *args, **kw):
878
835
        from bzrlib.commit import commit
879
836
        commit(self, *args, **kw)
880
837
        
881
838
 
882
 
    def lookup_revision(self, revision):
883
 
        """Return the revision identifier for a given revision information."""
884
 
        revno, info = self._get_revision_info(revision)
885
 
        return info
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
 
 
897
 
    def get_revision_info(self, revision):
898
 
        """Return (revno, revision id) for revision identifier.
899
 
 
900
 
        revision can be an integer, in which case it is assumed to be revno (though
901
 
            this will translate negative values into positive ones)
902
 
        revision can also be a string, in which case it is parsed for something like
903
 
            'date:' or 'revid:' etc.
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."""
 
839
    def lookup_revision(self, revno):
 
840
        """Return revision hash for revision number."""
912
841
        if revno == 0:
913
842
            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
 
        if revision is None:
934
 
            return 0, None
935
 
        revno = None
936
 
        try:# Convert to int if possible
937
 
            revision = int(revision)
938
 
        except ValueError:
939
 
            pass
940
 
        revs = self.revision_history()
941
 
        if isinstance(revision, int):
942
 
            if revision < 0:
943
 
                revno = len(revs) + revision + 1
944
 
            else:
945
 
                revno = revision
946
 
            rev_id = self.get_rev_id(revno, revs)
947
 
        elif isinstance(revision, basestring):
948
 
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
949
 
                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)
956
 
                    break
957
 
            else:
958
 
                raise BzrError('No namespace registered for string: %r' %
959
 
                               revision)
960
 
        else:
961
 
            raise TypeError('Unhandled revision type %s' % revision)
962
 
 
963
 
        if revno is None:
964
 
            if rev_id is None:
965
 
                raise bzrlib.errors.NoSuchRevision(self, revision)
966
 
        return revno, rev_id
967
 
 
968
 
    def _namespace_revno(self, revs, revision):
969
 
        """Lookup a revision by revision number"""
970
 
        assert revision.startswith('revno:')
971
 
        try:
972
 
            return (int(revision[6:]),)
973
 
        except ValueError:
974
 
            return None
975
 
    REVISION_NAMESPACES['revno:'] = _namespace_revno
976
 
 
977
 
    def _namespace_revid(self, revs, revision):
978
 
        assert revision.startswith('revid:')
979
 
        rev_id = revision[len('revid:'):]
980
 
        try:
981
 
            return revs.index(rev_id) + 1, rev_id
982
 
        except ValueError:
983
 
            return None, rev_id
984
 
    REVISION_NAMESPACES['revid:'] = _namespace_revid
985
 
 
986
 
    def _namespace_last(self, revs, revision):
987
 
        assert revision.startswith('last:')
988
 
        try:
989
 
            offset = int(revision[5:])
990
 
        except ValueError:
991
 
            return (None,)
992
 
        else:
993
 
            if offset <= 0:
994
 
                raise BzrError('You must supply a positive value for --revision last:XXX')
995
 
            return (len(revs) - offset + 1,)
996
 
    REVISION_NAMESPACES['last:'] = _namespace_last
997
 
 
998
 
    def _namespace_tag(self, revs, revision):
999
 
        assert revision.startswith('tag:')
1000
 
        raise BzrError('tag: namespace registered, but not implemented.')
1001
 
    REVISION_NAMESPACES['tag:'] = _namespace_tag
1002
 
 
1003
 
    def _namespace_date(self, revs, revision):
1004
 
        assert revision.startswith('date:')
1005
 
        import datetime
1006
 
        # Spec for date revisions:
1007
 
        #   date:value
1008
 
        #   value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
1009
 
        #   it can also start with a '+/-/='. '+' says match the first
1010
 
        #   entry after the given date. '-' is match the first entry before the date
1011
 
        #   '=' is match the first entry after, but still on the given date.
1012
 
        #
1013
 
        #   +2005-05-12 says find the first matching entry after May 12th, 2005 at 0:00
1014
 
        #   -2005-05-12 says find the first matching entry before May 12th, 2005 at 0:00
1015
 
        #   =2005-05-12 says find the first match after May 12th, 2005 at 0:00 but before
1016
 
        #       May 13th, 2005 at 0:00
1017
 
        #
1018
 
        #   So the proper way of saying 'give me all entries for today' is:
1019
 
        #       -r {date:+today}:{date:-tomorrow}
1020
 
        #   The default is '=' when not supplied
1021
 
        val = revision[5:]
1022
 
        match_style = '='
1023
 
        if val[:1] in ('+', '-', '='):
1024
 
            match_style = val[:1]
1025
 
            val = val[1:]
1026
 
 
1027
 
        today = datetime.datetime.today().replace(hour=0,minute=0,second=0,microsecond=0)
1028
 
        if val.lower() == 'yesterday':
1029
 
            dt = today - datetime.timedelta(days=1)
1030
 
        elif val.lower() == 'today':
1031
 
            dt = today
1032
 
        elif val.lower() == 'tomorrow':
1033
 
            dt = today + datetime.timedelta(days=1)
1034
 
        else:
1035
 
            import re
1036
 
            # This should be done outside the function to avoid recompiling it.
1037
 
            _date_re = re.compile(
1038
 
                    r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
1039
 
                    r'(,|T)?\s*'
1040
 
                    r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
1041
 
                )
1042
 
            m = _date_re.match(val)
1043
 
            if not m or (not m.group('date') and not m.group('time')):
1044
 
                raise BzrError('Invalid revision date %r' % revision)
1045
 
 
1046
 
            if m.group('date'):
1047
 
                year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
1048
 
            else:
1049
 
                year, month, day = today.year, today.month, today.day
1050
 
            if m.group('time'):
1051
 
                hour = int(m.group('hour'))
1052
 
                minute = int(m.group('minute'))
1053
 
                if m.group('second'):
1054
 
                    second = int(m.group('second'))
1055
 
                else:
1056
 
                    second = 0
1057
 
            else:
1058
 
                hour, minute, second = 0,0,0
1059
 
 
1060
 
            dt = datetime.datetime(year=year, month=month, day=day,
1061
 
                    hour=hour, minute=minute, second=second)
1062
 
        first = dt
1063
 
        last = None
1064
 
        reversed = False
1065
 
        if match_style == '-':
1066
 
            reversed = True
1067
 
        elif match_style == '=':
1068
 
            last = dt + datetime.timedelta(days=1)
1069
 
 
1070
 
        if reversed:
1071
 
            for i in range(len(revs)-1, -1, -1):
1072
 
                r = self.get_revision(revs[i])
1073
 
                # TODO: Handle timezone.
1074
 
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1075
 
                if first >= dt and (last is None or dt >= last):
1076
 
                    return (i+1,)
1077
 
        else:
1078
 
            for i in range(len(revs)):
1079
 
                r = self.get_revision(revs[i])
1080
 
                # TODO: Handle timezone.
1081
 
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1082
 
                if first <= dt and (last is None or dt <= last):
1083
 
                    return (i+1,)
1084
 
    REVISION_NAMESPACES['date:'] = _namespace_date
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
 
843
 
 
844
        try:
 
845
            # list is 0-based; revisions are 1-based
 
846
            return self.revision_history()[revno-1]
 
847
        except IndexError:
 
848
            raise BzrError("no such revision %s" % revno)
 
849
 
1105
850
 
1106
851
    def revision_tree(self, revision_id):
1107
852
        """Return Tree for a revision on this branch.
1108
853
 
1109
854
        `revision_id` may be None for the null revision, in which case
1110
855
        an `EmptyTree` is returned."""
 
856
        from bzrlib.tree import EmptyTree, RevisionTree
1111
857
        # TODO: refactor this to use an existing revision object
1112
858
        # so we don't need to read it in twice.
1113
859
        if revision_id == None:
1119
865
 
1120
866
    def working_tree(self):
1121
867
        """Return a `Tree` for the working copy."""
1122
 
        from bzrlib.workingtree import WorkingTree
 
868
        from workingtree import WorkingTree
1123
869
        return WorkingTree(self.base, self.read_working_inventory())
1124
870
 
1125
871
 
1128
874
 
1129
875
        If there are no revisions yet, return an `EmptyTree`.
1130
876
        """
 
877
        from bzrlib.tree import EmptyTree, RevisionTree
1131
878
        r = self.last_patch()
1132
879
        if r == None:
1133
880
            return EmptyTree()
1171
918
 
1172
919
            inv.rename(file_id, to_dir_id, to_tail)
1173
920
 
 
921
            print "%s => %s" % (from_rel, to_rel)
 
922
 
1174
923
            from_abs = self.abspath(from_rel)
1175
924
            to_abs = self.abspath(to_rel)
1176
925
            try:
1195
944
 
1196
945
        Note that to_name is only the last component of the new name;
1197
946
        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
947
        """
1202
 
        result = []
1203
948
        self.lock_write()
1204
949
        try:
1205
950
            ## TODO: Option to move IDs only
1240
985
            for f in from_paths:
1241
986
                name_tail = splitpath(f)[-1]
1242
987
                dest_path = appendpath(to_name, name_tail)
1243
 
                result.append((f, dest_path))
 
988
                print "%s => %s" % (f, dest_path)
1244
989
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1245
990
                try:
1246
991
                    os.rename(self.abspath(f), self.abspath(dest_path))
1252
997
        finally:
1253
998
            self.unlock()
1254
999
 
1255
 
        return result
1256
 
 
1257
1000
 
1258
1001
    def revert(self, filenames, old_tree=None, backups=True):
1259
1002
        """Restore selected files to the versions from a previous tree.
1341
1084
            self.unlock()
1342
1085
 
1343
1086
 
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
1087
 
1395
1088
class ScratchBranch(Branch):
1396
1089
    """Special test class: a branch that cleans up after itself.
1438
1131
        os.rmdir(base)
1439
1132
        copytree(self.base, base, symlinks=True)
1440
1133
        return ScratchBranch(base=base)
1441
 
 
1442
 
 
1443
1134
        
1444
1135
    def __del__(self):
1445
1136
        self.destroy()
1509
1200
 
1510
1201
    s = hexlify(rand_bytes(8))
1511
1202
    return '-'.join((name, compact_date(time()), s))
1512
 
 
1513
 
 
1514
 
def gen_root_id():
1515
 
    """Return a new tree-root file id."""
1516
 
    return gen_file_id('TREE_ROOT')
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):]