/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: Robert Collins
  • Date: 2005-09-26 08:56:15 UTC
  • mto: (1092.3.4)
  • mto: This revision was merged to the branch mainline in revision 1390.
  • Revision ID: robertc@robertcollins.net-20050926085615-99b8fb35f41b541d
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid

Show diffs side-by-side

added added

removed removed

Lines of Context:
21
21
import bzrlib
22
22
from bzrlib.trace import mutter, note
23
23
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
24
 
     splitpath, \
25
 
     sha_file, appendpath, file_kind
26
 
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId
27
 
import bzrlib.errors
 
24
     rename, splitpath, sha_file, appendpath, file_kind
 
25
 
 
26
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId, \
 
27
     DivergedBranches, NotBranchError
28
28
from bzrlib.textui import show_status
29
29
from bzrlib.revision import Revision
30
 
from bzrlib.xml import unpack_xml
31
30
from bzrlib.delta import compare_trees
32
31
from bzrlib.tree import EmptyTree, RevisionTree
33
 
        
 
32
import bzrlib.xml
 
33
import bzrlib.ui
 
34
 
 
35
 
 
36
 
34
37
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
35
38
## TODO: Maybe include checks for common corruption of newlines, etc?
36
39
 
39
42
# repeatedly to calculate deltas.  We could perhaps have a weakref
40
43
# cache in memory to make this faster.
41
44
 
42
 
 
43
 
def find_branch(f, **args):
44
 
    if f and (f.startswith('http://') or f.startswith('https://')):
45
 
        import remotebranch 
46
 
        return remotebranch.RemoteBranch(f, **args)
47
 
    else:
48
 
        return Branch(f, **args)
49
 
 
50
 
 
51
 
def find_cached_branch(f, cache_root, **args):
52
 
    from remotebranch import RemoteBranch
53
 
    br = find_branch(f, **args)
54
 
    def cacheify(br, store_name):
55
 
        from meta_store import CachedStore
56
 
        cache_path = os.path.join(cache_root, store_name)
57
 
        os.mkdir(cache_path)
58
 
        new_store = CachedStore(getattr(br, store_name), cache_path)
59
 
        setattr(br, store_name, new_store)
60
 
 
61
 
    if isinstance(br, RemoteBranch):
62
 
        cacheify(br, 'inventory_store')
63
 
        cacheify(br, 'text_store')
64
 
        cacheify(br, 'revision_store')
65
 
    return br
66
 
 
 
45
def find_branch(*ignored, **ignored_too):
 
46
    # XXX: leave this here for about one release, then remove it
 
47
    raise NotImplementedError('find_branch() is not supported anymore, '
 
48
                              'please use one of the new branch constructors')
67
49
 
68
50
def _relpath(base, path):
69
51
    """Return path relative to base, or raise exception.
87
69
        if tail:
88
70
            s.insert(0, tail)
89
71
    else:
90
 
        from errors import NotBranchError
91
72
        raise NotBranchError("path %r is not within branch %r" % (rp, base))
92
73
 
93
74
    return os.sep.join(s)
101
82
    It is not necessary that f exists.
102
83
 
103
84
    Basically we keep looking up until we find the control directory or
104
 
    run into the root."""
 
85
    run into the root.  If there isn't one, raises NotBranchError.
 
86
    """
105
87
    if f == None:
106
88
        f = os.getcwd()
107
89
    elif hasattr(os.path, 'realpath'):
120
102
        head, tail = os.path.split(f)
121
103
        if head == f:
122
104
            # reached the root, whatever that may be
123
 
            raise BzrError('%r is not in a branch' % orig_f)
 
105
            raise NotBranchError('%s is not in a branch' % orig_f)
124
106
        f = head
125
 
    
126
 
class DivergedBranches(Exception):
127
 
    def __init__(self, branch1, branch2):
128
 
        self.branch1 = branch1
129
 
        self.branch2 = branch2
130
 
        Exception.__init__(self, "These branches have diverged.")
 
107
 
 
108
 
131
109
 
132
110
 
133
111
######################################################################
137
115
    """Branch holding a history of revisions.
138
116
 
139
117
    base
140
 
        Base directory of the branch.
 
118
        Base directory/url of the branch.
 
119
    """
 
120
    base = None
 
121
 
 
122
    def __init__(self, *ignored, **ignored_too):
 
123
        raise NotImplementedError('The Branch class is abstract')
 
124
 
 
125
    @staticmethod
 
126
    def open(base):
 
127
        """Open an existing branch, rooted at 'base' (url)"""
 
128
        if base and (base.startswith('http://') or base.startswith('https://')):
 
129
            from bzrlib.remotebranch import RemoteBranch
 
130
            return RemoteBranch(base, find_root=False)
 
131
        else:
 
132
            return LocalBranch(base, find_root=False)
 
133
 
 
134
    @staticmethod
 
135
    def open_containing(url):
 
136
        """Open an existing branch which contains url.
 
137
        
 
138
        This probes for a branch at url, and searches upwards from there.
 
139
        """
 
140
        if url and (url.startswith('http://') or url.startswith('https://')):
 
141
            from bzrlib.remotebranch import RemoteBranch
 
142
            return RemoteBranch(url)
 
143
        else:
 
144
            return LocalBranch(url)
 
145
 
 
146
    @staticmethod
 
147
    def initialize(base):
 
148
        """Create a new branch, rooted at 'base' (url)"""
 
149
        if base and (base.startswith('http://') or base.startswith('https://')):
 
150
            from bzrlib.remotebranch import RemoteBranch
 
151
            return RemoteBranch(base, init=True)
 
152
        else:
 
153
            return LocalBranch(base, init=True)
 
154
 
 
155
    def setup_caching(self, cache_root):
 
156
        """Subclasses that care about caching should override this, and set
 
157
        up cached stores located under cache_root.
 
158
        """
 
159
 
 
160
 
 
161
class LocalBranch(Branch):
 
162
    """A branch stored in the actual filesystem.
 
163
 
 
164
    Note that it's "local" in the context of the filesystem; it doesn't
 
165
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
 
166
    it's writable, and can be accessed via the normal filesystem API.
141
167
 
142
168
    _lock_mode
143
169
        None, or 'r' or 'w'
149
175
    _lock
150
176
        Lock object from bzrlib.lock.
151
177
    """
152
 
    base = None
 
178
    # We actually expect this class to be somewhat short-lived; part of its
 
179
    # purpose is to try to isolate what bits of the branch logic are tied to
 
180
    # filesystem access, so that in a later step, we can extricate them to
 
181
    # a separarte ("storage") class.
153
182
    _lock_mode = None
154
183
    _lock_count = None
155
184
    _lock = None
156
 
    
157
 
    # Map some sort of prefix into a namespace
158
 
    # stuff like "revno:10", "revid:", etc.
159
 
    # This should match a prefix with a function which accepts
160
 
    REVISION_NAMESPACES = {}
161
185
 
162
186
    def __init__(self, base, init=False, find_root=True):
163
187
        """Create new branch object at a particular location.
164
188
 
165
 
        base -- Base directory for the branch.
 
189
        base -- Base directory for the branch. May be a file:// url.
166
190
        
167
191
        init -- If True, create new control files in a previously
168
192
             unversioned directory.  If False, the branch must already
181
205
        elif find_root:
182
206
            self.base = find_branch_root(base)
183
207
        else:
 
208
            if base.startswith("file://"):
 
209
                base = base[7:]
184
210
            self.base = os.path.realpath(base)
185
211
            if not isdir(self.controlfilename('.')):
186
 
                from errors import NotBranchError
187
212
                raise NotBranchError("not a bzr branch: %s" % quotefn(base),
188
213
                                     ['use "bzr init" to initialize a new working tree',
189
214
                                      'current bzr can only operate from top-of-tree'])
203
228
 
204
229
    def __del__(self):
205
230
        if self._lock_mode or self._lock:
206
 
            from warnings import warn
 
231
            from bzrlib.warnings import warn
207
232
            warn("branch %r was not explicitly unlocked" % self)
208
233
            self._lock.unlock()
209
234
 
210
 
 
211
 
 
212
235
    def lock_write(self):
213
236
        if self._lock_mode:
214
237
            if self._lock_mode != 'w':
215
 
                from errors import LockError
 
238
                from bzrlib.errors import LockError
216
239
                raise LockError("can't upgrade to a write lock from %r" %
217
240
                                self._lock_mode)
218
241
            self._lock_count += 1
224
247
            self._lock_count = 1
225
248
 
226
249
 
227
 
 
228
250
    def lock_read(self):
229
251
        if self._lock_mode:
230
252
            assert self._lock_mode in ('r', 'w'), \
237
259
            self._lock_mode = 'r'
238
260
            self._lock_count = 1
239
261
                        
240
 
 
241
 
            
242
262
    def unlock(self):
243
263
        if not self._lock_mode:
244
 
            from errors import LockError
 
264
            from bzrlib.errors import LockError
245
265
            raise LockError('branch %r is not locked' % (self))
246
266
 
247
267
        if self._lock_count > 1:
251
271
            self._lock = None
252
272
            self._lock_mode = self._lock_count = None
253
273
 
254
 
 
255
274
    def abspath(self, name):
256
275
        """Return absolute filename for something in the branch"""
257
276
        return os.path.join(self.base, name)
258
277
 
259
 
 
260
278
    def relpath(self, path):
261
279
        """Return path relative to this branch of something inside it.
262
280
 
263
281
        Raises an error if path is not in this branch."""
264
282
        return _relpath(self.base, path)
265
283
 
266
 
 
267
284
    def controlfilename(self, file_or_path):
268
285
        """Return location relative to branch."""
269
286
        if isinstance(file_or_path, basestring):
296
313
        else:
297
314
            raise BzrError("invalid controlfile mode %r" % mode)
298
315
 
299
 
 
300
 
 
301
316
    def _make_control(self):
302
317
        from bzrlib.inventory import Inventory
303
 
        from bzrlib.xml import pack_xml
304
318
        
305
319
        os.mkdir(self.controlfilename([]))
306
320
        self.controlfile('README', 'w').write(
316
330
            self.controlfile(f, 'w').write('')
317
331
        mutter('created control directory in ' + self.base)
318
332
 
319
 
        pack_xml(Inventory(gen_root_id()), self.controlfile('inventory','w'))
 
333
        # if we want per-tree root ids then this is the place to set
 
334
        # them; they're not needed for now and so ommitted for
 
335
        # simplicity.
 
336
        f = self.controlfile('inventory','w')
 
337
        bzrlib.xml.serializer_v4.write_inventory(Inventory(), f)
320
338
 
321
339
 
322
340
    def _check_format(self):
331
349
        # on Windows from Linux and so on.  I think it might be better
332
350
        # to always make all internal files in unix format.
333
351
        fmt = self.controlfile('branch-format', 'r').read()
334
 
        fmt.replace('\r\n', '')
 
352
        fmt = fmt.replace('\r\n', '\n')
335
353
        if fmt != BZR_BRANCH_FORMAT:
336
354
            raise BzrError('sorry, branch format %r not supported' % fmt,
337
355
                           ['use a different bzr version',
357
375
    def read_working_inventory(self):
358
376
        """Read the working inventory."""
359
377
        from bzrlib.inventory import Inventory
360
 
        from bzrlib.xml import unpack_xml
361
 
        from time import time
362
 
        before = time()
363
378
        self.lock_read()
364
379
        try:
365
380
            # ElementTree does its own conversion from UTF-8, so open in
366
381
            # 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
 
382
            f = self.controlfile('inventory', 'rb')
 
383
            return bzrlib.xml.serializer_v4.read_inventory(f)
372
384
        finally:
373
385
            self.unlock()
374
386
            
380
392
        will be committed to the next revision.
381
393
        """
382
394
        from bzrlib.atomicfile import AtomicFile
383
 
        from bzrlib.xml import pack_xml
384
395
        
385
396
        self.lock_write()
386
397
        try:
387
398
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
388
399
            try:
389
 
                pack_xml(inv, f)
 
400
                bzrlib.xml.serializer_v4.write_inventory(inv, f)
390
401
                f.commit()
391
402
            finally:
392
403
                f.close()
400
411
                         """Inventory for the working copy.""")
401
412
 
402
413
 
403
 
    def add(self, files, verbose=False, ids=None):
 
414
    def add(self, files, ids=None):
404
415
        """Make files versioned.
405
416
 
406
 
        Note that the command line normally calls smart_add instead.
 
417
        Note that the command line normally calls smart_add instead,
 
418
        which can automatically recurse.
407
419
 
408
420
        This puts the files in the Added state, so that they will be
409
421
        recorded by the next commit.
419
431
        TODO: Perhaps have an option to add the ids even if the files do
420
432
              not (yet) exist.
421
433
 
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.
 
434
        TODO: Perhaps yield the ids and paths as they're added.
428
435
        """
429
436
        # TODO: Re-adding a file that is removed in the working copy
430
437
        # should probably put it back with the previous ID.
466
473
                    file_id = gen_file_id(f)
467
474
                inv.add_path(f, kind=kind, file_id=file_id)
468
475
 
469
 
                if verbose:
470
 
                    print 'added', quotefn(f)
471
 
 
472
476
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
473
477
 
474
478
            self._write_inventory(inv)
480
484
        """Print `file` to stdout."""
481
485
        self.lock_read()
482
486
        try:
483
 
            tree = self.revision_tree(self.lookup_revision(revno))
 
487
            tree = self.revision_tree(self.get_rev_id(revno))
484
488
            # use inventory as it was in that revision
485
489
            file_id = tree.inventory.path2id(file)
486
490
            if not file_id:
584
588
            f.close()
585
589
 
586
590
 
587
 
    def get_revision_xml(self, revision_id):
 
591
    def get_revision_xml_file(self, revision_id):
588
592
        """Return XML file object for revision object."""
589
593
        if not revision_id or not isinstance(revision_id, basestring):
590
594
            raise InvalidRevisionId(revision_id)
593
597
        try:
594
598
            try:
595
599
                return self.revision_store[revision_id]
596
 
            except IndexError:
597
 
                raise bzrlib.errors.NoSuchRevision(revision_id)
 
600
            except (IndexError, KeyError):
 
601
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
598
602
        finally:
599
603
            self.unlock()
600
604
 
601
605
 
 
606
    #deprecated
 
607
    get_revision_xml = get_revision_xml_file
 
608
 
 
609
 
602
610
    def get_revision(self, revision_id):
603
611
        """Return the Revision object for a named revision"""
604
 
        xml_file = self.get_revision_xml(revision_id)
 
612
        xml_file = self.get_revision_xml_file(revision_id)
605
613
 
606
614
        try:
607
 
            r = unpack_xml(Revision, xml_file)
 
615
            r = bzrlib.xml.serializer_v4.read_revision(xml_file)
608
616
        except SyntaxError, e:
609
617
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
610
618
                                         [revision_id,
655
663
               parameter which can be either an integer revno or a
656
664
               string hash."""
657
665
        from bzrlib.inventory import Inventory
658
 
        from bzrlib.xml import unpack_xml
659
 
 
660
 
        return unpack_xml(Inventory, self.inventory_store[inventory_id])
 
666
 
 
667
        f = self.get_inventory_xml_file(inventory_id)
 
668
        return bzrlib.xml.serializer_v4.read_inventory(f)
 
669
 
 
670
 
 
671
    def get_inventory_xml(self, inventory_id):
 
672
        """Get inventory XML as a file object."""
 
673
        return self.inventory_store[inventory_id]
 
674
 
 
675
    get_inventory_xml_file = get_inventory_xml
661
676
            
662
677
 
663
678
    def get_inventory_sha1(self, inventory_id):
664
679
        """Return the sha1 hash of the inventory entry
665
680
        """
666
 
        return sha_file(self.inventory_store[inventory_id])
 
681
        return sha_file(self.get_inventory_xml(inventory_id))
667
682
 
668
683
 
669
684
    def get_revision_inventory(self, revision_id):
693
708
 
694
709
    def common_ancestor(self, other, self_revno=None, other_revno=None):
695
710
        """
696
 
        >>> import commit
 
711
        >>> from bzrlib.commit import commit
697
712
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
698
713
        >>> sb.common_ancestor(sb) == (None, None)
699
714
        True
700
 
        >>> commit.commit(sb, "Committing first revision", verbose=False)
 
715
        >>> commit(sb, "Committing first revision", verbose=False)
701
716
        >>> sb.common_ancestor(sb)[0]
702
717
        1
703
718
        >>> clone = sb.clone()
704
 
        >>> commit.commit(sb, "Committing second revision", verbose=False)
 
719
        >>> commit(sb, "Committing second revision", verbose=False)
705
720
        >>> sb.common_ancestor(sb)[0]
706
721
        2
707
722
        >>> sb.common_ancestor(clone)[0]
708
723
        1
709
 
        >>> commit.commit(clone, "Committing divergent second revision", 
 
724
        >>> commit(clone, "Committing divergent second revision", 
710
725
        ...               verbose=False)
711
726
        >>> sb.common_ancestor(clone)[0]
712
727
        1
755
770
            return None
756
771
 
757
772
 
758
 
    def missing_revisions(self, other, stop_revision=None):
 
773
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
759
774
        """
760
775
        If self and other have not diverged, return a list of the revisions
761
776
        present in other, but missing from self.
794
809
        if stop_revision is None:
795
810
            stop_revision = other_len
796
811
        elif stop_revision > other_len:
797
 
            raise NoSuchRevision(self, stop_revision)
 
812
            raise bzrlib.errors.NoSuchRevision(self, stop_revision)
798
813
        
799
814
        return other_history[self_len:stop_revision]
800
815
 
801
816
 
802
817
    def update_revisions(self, other, stop_revision=None):
803
818
        """Pull in all new revisions from other branch.
804
 
        
805
 
        >>> from bzrlib.commit import commit
806
 
        >>> bzrlib.trace.silent = True
807
 
        >>> br1 = ScratchBranch(files=['foo', 'bar'])
808
 
        >>> br1.add('foo')
809
 
        >>> br1.add('bar')
810
 
        >>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
811
 
        >>> br2 = ScratchBranch()
812
 
        >>> br2.update_revisions(br1)
813
 
        Added 2 texts.
814
 
        Added 1 inventories.
815
 
        Added 1 revisions.
816
 
        >>> br2.revision_history()
817
 
        [u'REVISION-ID-1']
818
 
        >>> br2.update_revisions(br1)
819
 
        Added 0 texts.
820
 
        Added 0 inventories.
821
 
        Added 0 revisions.
822
 
        >>> br1.text_store.total_size() == br2.text_store.total_size()
823
 
        True
824
819
        """
825
 
        from bzrlib.progress import ProgressBar
826
 
 
827
 
        pb = ProgressBar()
828
 
 
 
820
        from bzrlib.fetch import greedy_fetch
 
821
        from bzrlib.revision import get_intervening_revisions
 
822
 
 
823
        pb = bzrlib.ui.ui_factory.progress_bar()
829
824
        pb.update('comparing histories')
830
 
        revision_ids = self.missing_revisions(other, stop_revision)
831
 
 
 
825
        if stop_revision is None:
 
826
            other_revision = other.last_patch()
 
827
        else:
 
828
            other_revision = other.get_rev_id(stop_revision)
 
829
        count = greedy_fetch(self, other, other_revision, pb)[0]
 
830
        try:
 
831
            revision_ids = self.missing_revisions(other, stop_revision)
 
832
        except DivergedBranches, e:
 
833
            try:
 
834
                revision_ids = get_intervening_revisions(self.last_patch(), 
 
835
                                                         other_revision, self)
 
836
                assert self.last_patch() not in revision_ids
 
837
            except bzrlib.errors.NotAncestor:
 
838
                raise e
 
839
 
 
840
        self.append_revision(*revision_ids)
 
841
        pb.clear()
 
842
 
 
843
    def install_revisions(self, other, revision_ids, pb):
832
844
        if hasattr(other.revision_store, "prefetch"):
833
845
            other.revision_store.prefetch(revision_ids)
834
846
        if hasattr(other.inventory_store, "prefetch"):
835
 
            inventory_ids = [other.get_revision(r).inventory_id
836
 
                             for r in revision_ids]
 
847
            inventory_ids = []
 
848
            for rev_id in revision_ids:
 
849
                try:
 
850
                    revision = other.get_revision(rev_id).inventory_id
 
851
                    inventory_ids.append(revision)
 
852
                except bzrlib.errors.NoSuchRevision:
 
853
                    pass
837
854
            other.inventory_store.prefetch(inventory_ids)
 
855
 
 
856
        if pb is None:
 
857
            pb = bzrlib.ui.ui_factory.progress_bar()
838
858
                
839
859
        revisions = []
840
860
        needed_texts = set()
841
861
        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)
 
862
 
 
863
        failures = set()
 
864
        for i, rev_id in enumerate(revision_ids):
 
865
            pb.update('fetching revision', i+1, len(revision_ids))
 
866
            try:
 
867
                rev = other.get_revision(rev_id)
 
868
            except bzrlib.errors.NoSuchRevision:
 
869
                failures.add(rev_id)
 
870
                continue
 
871
 
846
872
            revisions.append(rev)
847
873
            inv = other.get_inventory(str(rev.inventory_id))
848
874
            for key, entry in inv.iter_entries():
853
879
 
854
880
        pb.clear()
855
881
                    
856
 
        count = self.text_store.copy_multi(other.text_store, needed_texts)
857
 
        print "Added %d texts." % count 
 
882
        count, cp_fail = self.text_store.copy_multi(other.text_store, 
 
883
                                                    needed_texts)
 
884
        #print "Added %d texts." % count 
858
885
        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 
 
886
        count, cp_fail = self.inventory_store.copy_multi(other.inventory_store, 
 
887
                                                         inventory_ids)
 
888
        #print "Added %d inventories." % count 
862
889
        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
 
        
 
890
 
 
891
        count, cp_fail = self.revision_store.copy_multi(other.revision_store, 
 
892
                                                          revision_ids,
 
893
                                                          permit_failure=True)
 
894
        assert len(cp_fail) == 0 
 
895
        return count, failures
 
896
       
 
897
 
870
898
    def commit(self, *args, **kw):
871
899
        from bzrlib.commit import commit
872
900
        commit(self, *args, **kw)
873
901
        
874
 
 
875
 
    def lookup_revision(self, revision):
876
 
        """Return the revision identifier for a given revision information."""
877
 
        revno, info = self.get_revision_info(revision)
878
 
        return info
879
 
 
880
 
    def get_revision_info(self, revision):
881
 
        """Return (revno, revision id) for revision identifier.
882
 
 
883
 
        revision can be an integer, in which case it is assumed to be revno (though
884
 
            this will translate negative values into positive ones)
885
 
        revision can also be a string, in which case it is parsed for something like
886
 
            'date:' or 'revid:' etc.
887
 
        """
888
 
        if revision is None:
889
 
            return 0, None
890
 
        revno = None
891
 
        try:# Convert to int if possible
892
 
            revision = int(revision)
893
 
        except ValueError:
894
 
            pass
895
 
        revs = self.revision_history()
896
 
        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
 
            if revision < 0:
901
 
                revno = len(revs) + revision + 1
902
 
            else:
903
 
                revno = revision
904
 
        elif isinstance(revision, basestring):
905
 
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
906
 
                if revision.startswith(prefix):
907
 
                    revno = func(self, revs, revision)
908
 
                    break
909
 
            else:
910
 
                raise BzrError('No namespace registered for string: %r' % revision)
911
 
 
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]
915
 
 
916
 
    def _namespace_revno(self, revs, revision):
917
 
        """Lookup a revision by revision number"""
918
 
        assert revision.startswith('revno:')
919
 
        try:
920
 
            return int(revision[6:])
921
 
        except ValueError:
922
 
            return None
923
 
    REVISION_NAMESPACES['revno:'] = _namespace_revno
924
 
 
925
 
    def _namespace_revid(self, revs, revision):
926
 
        assert revision.startswith('revid:')
927
 
        try:
928
 
            return revs.index(revision[6:]) + 1
929
 
        except ValueError:
930
 
            return None
931
 
    REVISION_NAMESPACES['revid:'] = _namespace_revid
932
 
 
933
 
    def _namespace_last(self, revs, revision):
934
 
        assert revision.startswith('last:')
935
 
        try:
936
 
            offset = int(revision[5:])
937
 
        except ValueError:
938
 
            return None
939
 
        else:
940
 
            if offset <= 0:
941
 
                raise BzrError('You must supply a positive value for --revision last:XXX')
942
 
            return len(revs) - offset + 1
943
 
    REVISION_NAMESPACES['last:'] = _namespace_last
944
 
 
945
 
    def _namespace_tag(self, revs, revision):
946
 
        assert revision.startswith('tag:')
947
 
        raise BzrError('tag: namespace registered, but not implemented.')
948
 
    REVISION_NAMESPACES['tag:'] = _namespace_tag
949
 
 
950
 
    def _namespace_date(self, revs, revision):
951
 
        assert revision.startswith('date:')
952
 
        import datetime
953
 
        # Spec for date revisions:
954
 
        #   date:value
955
 
        #   value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
956
 
        #   it can also start with a '+/-/='. '+' says match the first
957
 
        #   entry after the given date. '-' is match the first entry before the date
958
 
        #   '=' is match the first entry after, but still on the given date.
959
 
        #
960
 
        #   +2005-05-12 says find the first matching entry after May 12th, 2005 at 0:00
961
 
        #   -2005-05-12 says find the first matching entry before May 12th, 2005 at 0:00
962
 
        #   =2005-05-12 says find the first match after May 12th, 2005 at 0:00 but before
963
 
        #       May 13th, 2005 at 0:00
964
 
        #
965
 
        #   So the proper way of saying 'give me all entries for today' is:
966
 
        #       -r {date:+today}:{date:-tomorrow}
967
 
        #   The default is '=' when not supplied
968
 
        val = revision[5:]
969
 
        match_style = '='
970
 
        if val[:1] in ('+', '-', '='):
971
 
            match_style = val[:1]
972
 
            val = val[1:]
973
 
 
974
 
        today = datetime.datetime.today().replace(hour=0,minute=0,second=0,microsecond=0)
975
 
        if val.lower() == 'yesterday':
976
 
            dt = today - datetime.timedelta(days=1)
977
 
        elif val.lower() == 'today':
978
 
            dt = today
979
 
        elif val.lower() == 'tomorrow':
980
 
            dt = today + datetime.timedelta(days=1)
981
 
        else:
982
 
            import re
983
 
            # This should be done outside the function to avoid recompiling it.
984
 
            _date_re = re.compile(
985
 
                    r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
986
 
                    r'(,|T)?\s*'
987
 
                    r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
988
 
                )
989
 
            m = _date_re.match(val)
990
 
            if not m or (not m.group('date') and not m.group('time')):
991
 
                raise BzrError('Invalid revision date %r' % revision)
992
 
 
993
 
            if m.group('date'):
994
 
                year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
995
 
            else:
996
 
                year, month, day = today.year, today.month, today.day
997
 
            if m.group('time'):
998
 
                hour = int(m.group('hour'))
999
 
                minute = int(m.group('minute'))
1000
 
                if m.group('second'):
1001
 
                    second = int(m.group('second'))
1002
 
                else:
1003
 
                    second = 0
1004
 
            else:
1005
 
                hour, minute, second = 0,0,0
1006
 
 
1007
 
            dt = datetime.datetime(year=year, month=month, day=day,
1008
 
                    hour=hour, minute=minute, second=second)
1009
 
        first = dt
1010
 
        last = None
1011
 
        reversed = False
1012
 
        if match_style == '-':
1013
 
            reversed = True
1014
 
        elif match_style == '=':
1015
 
            last = dt + datetime.timedelta(days=1)
1016
 
 
1017
 
        if reversed:
1018
 
            for i in range(len(revs)-1, -1, -1):
1019
 
                r = self.get_revision(revs[i])
1020
 
                # TODO: Handle timezone.
1021
 
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1022
 
                if first >= dt and (last is None or dt >= last):
1023
 
                    return i+1
1024
 
        else:
1025
 
            for i in range(len(revs)):
1026
 
                r = self.get_revision(revs[i])
1027
 
                # TODO: Handle timezone.
1028
 
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1029
 
                if first <= dt and (last is None or dt <= last):
1030
 
                    return i+1
1031
 
    REVISION_NAMESPACES['date:'] = _namespace_date
 
902
    def revision_id_to_revno(self, revision_id):
 
903
        """Given a revision id, return its revno"""
 
904
        history = self.revision_history()
 
905
        try:
 
906
            return history.index(revision_id) + 1
 
907
        except ValueError:
 
908
            raise bzrlib.errors.NoSuchRevision(self, revision_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
 
1032
920
 
1033
921
    def revision_tree(self, revision_id):
1034
922
        """Return Tree for a revision on this branch.
1046
934
 
1047
935
    def working_tree(self):
1048
936
        """Return a `Tree` for the working copy."""
1049
 
        from workingtree import WorkingTree
 
937
        from bzrlib.workingtree import WorkingTree
1050
938
        return WorkingTree(self.base, self.read_working_inventory())
1051
939
 
1052
940
 
1098
986
 
1099
987
            inv.rename(file_id, to_dir_id, to_tail)
1100
988
 
1101
 
            print "%s => %s" % (from_rel, to_rel)
1102
 
 
1103
989
            from_abs = self.abspath(from_rel)
1104
990
            to_abs = self.abspath(to_rel)
1105
991
            try:
1106
 
                os.rename(from_abs, to_abs)
 
992
                rename(from_abs, to_abs)
1107
993
            except OSError, e:
1108
994
                raise BzrError("failed to rename %r to %r: %s"
1109
995
                        % (from_abs, to_abs, e[1]),
1124
1010
 
1125
1011
        Note that to_name is only the last component of the new name;
1126
1012
        this doesn't change the directory.
 
1013
 
 
1014
        This returns a list of (from_path, to_path) pairs for each
 
1015
        entry that is moved.
1127
1016
        """
 
1017
        result = []
1128
1018
        self.lock_write()
1129
1019
        try:
1130
1020
            ## TODO: Option to move IDs only
1165
1055
            for f in from_paths:
1166
1056
                name_tail = splitpath(f)[-1]
1167
1057
                dest_path = appendpath(to_name, name_tail)
1168
 
                print "%s => %s" % (f, dest_path)
 
1058
                result.append((f, dest_path))
1169
1059
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1170
1060
                try:
1171
 
                    os.rename(self.abspath(f), self.abspath(dest_path))
 
1061
                    rename(self.abspath(f), self.abspath(dest_path))
1172
1062
                except OSError, e:
1173
1063
                    raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1174
1064
                            ["rename rolled back"])
1177
1067
        finally:
1178
1068
            self.unlock()
1179
1069
 
 
1070
        return result
 
1071
 
1180
1072
 
1181
1073
    def revert(self, filenames, old_tree=None, backups=True):
1182
1074
        """Restore selected files to the versions from a previous tree.
1264
1156
            self.unlock()
1265
1157
 
1266
1158
 
1267
 
 
1268
 
class ScratchBranch(Branch):
 
1159
    def get_parent(self):
 
1160
        """Return the parent location of the branch.
 
1161
 
 
1162
        This is the default location for push/pull/missing.  The usual
 
1163
        pattern is that the user can override it by specifying a
 
1164
        location.
 
1165
        """
 
1166
        import errno
 
1167
        _locs = ['parent', 'pull', 'x-pull']
 
1168
        for l in _locs:
 
1169
            try:
 
1170
                return self.controlfile(l, 'r').read().strip('\n')
 
1171
            except IOError, e:
 
1172
                if e.errno != errno.ENOENT:
 
1173
                    raise
 
1174
        return None
 
1175
 
 
1176
 
 
1177
    def set_parent(self, url):
 
1178
        # TODO: Maybe delete old location files?
 
1179
        from bzrlib.atomicfile import AtomicFile
 
1180
        self.lock_write()
 
1181
        try:
 
1182
            f = AtomicFile(self.controlfilename('parent'))
 
1183
            try:
 
1184
                f.write(url + '\n')
 
1185
                f.commit()
 
1186
            finally:
 
1187
                f.close()
 
1188
        finally:
 
1189
            self.unlock()
 
1190
 
 
1191
    def check_revno(self, revno):
 
1192
        """\
 
1193
        Check whether a revno corresponds to any revision.
 
1194
        Zero (the NULL revision) is considered valid.
 
1195
        """
 
1196
        if revno != 0:
 
1197
            self.check_real_revno(revno)
 
1198
            
 
1199
    def check_real_revno(self, revno):
 
1200
        """\
 
1201
        Check whether a revno corresponds to a real revision.
 
1202
        Zero (the NULL revision) is considered invalid
 
1203
        """
 
1204
        if revno < 1 or revno > self.revno():
 
1205
            raise InvalidRevisionNumber(revno)
 
1206
        
 
1207
        
 
1208
        
 
1209
 
 
1210
 
 
1211
class ScratchBranch(LocalBranch):
1269
1212
    """Special test class: a branch that cleans up after itself.
1270
1213
 
1271
1214
    >>> b = ScratchBranch()
1288
1231
        if base is None:
1289
1232
            base = mkdtemp()
1290
1233
            init = True
1291
 
        Branch.__init__(self, base, init=init)
 
1234
        LocalBranch.__init__(self, base, init=init)
1292
1235
        for d in dirs:
1293
1236
            os.mkdir(self.abspath(d))
1294
1237
            
1300
1243
        """
1301
1244
        >>> orig = ScratchBranch(files=["file1", "file2"])
1302
1245
        >>> clone = orig.clone()
1303
 
        >>> os.path.samefile(orig.base, clone.base)
 
1246
        >>> if os.name != 'nt':
 
1247
        ...   os.path.samefile(orig.base, clone.base)
 
1248
        ... else:
 
1249
        ...   orig.base == clone.base
 
1250
        ...
1304
1251
        False
1305
1252
        >>> os.path.isfile(os.path.join(clone.base, "file1"))
1306
1253
        True
1311
1258
        os.rmdir(base)
1312
1259
        copytree(self.base, base, symlinks=True)
1313
1260
        return ScratchBranch(base=base)
 
1261
 
 
1262
 
1314
1263
        
1315
1264
    def __del__(self):
1316
1265
        self.destroy()
1386
1335
    """Return a new tree-root file id."""
1387
1336
    return gen_file_id('TREE_ROOT')
1388
1337
 
 
1338
 
 
1339
def copy_branch(branch_from, to_location, revno=None):
 
1340
    """Copy branch_from into the existing directory to_location.
 
1341
 
 
1342
    revision
 
1343
        If not None, only revisions up to this point will be copied.
 
1344
        The head of the new branch will be that revision.
 
1345
 
 
1346
    to_location
 
1347
        The name of a local directory that exists but is empty.
 
1348
    """
 
1349
    from bzrlib.merge import merge
 
1350
 
 
1351
    assert isinstance(branch_from, Branch)
 
1352
    assert isinstance(to_location, basestring)
 
1353
    
 
1354
    br_to = Branch.initialize(to_location)
 
1355
    br_to.set_root_id(branch_from.get_root_id())
 
1356
    if revno is None:
 
1357
        revno = branch_from.revno()
 
1358
    br_to.update_revisions(branch_from, stop_revision=revno)
 
1359
    merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
1360
          check_clean=False, ignore_zero=True)
 
1361
    br_to.set_parent(branch_from.base)
 
1362
    return br_to