/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-27 07:24:40 UTC
  • mfrom: (1185.1.41)
  • Revision ID: robertc@robertcollins.net-20050927072440-1bf4d99c3e1db5b3
pair programming worx... merge integration and weave

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
 
18
18
import sys
19
19
import os
 
20
import errno
 
21
from warnings import warn
 
22
 
20
23
 
21
24
import bzrlib
22
25
from bzrlib.trace import mutter, note
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
 
26
from bzrlib.osutils import (isdir, quotefn, compact_date, rand_bytes, 
 
27
                            rename, splitpath, sha_file, appendpath, 
 
28
                            file_kind)
 
29
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
 
30
                           NoSuchRevision, HistoryMissing, NotBranchError,
 
31
                           DivergedBranches, LockError)
28
32
from bzrlib.textui import show_status
29
 
from bzrlib.revision import Revision
30
 
from bzrlib.xml import unpack_xml
 
33
from bzrlib.revision import Revision, validate_revision_id
31
34
from bzrlib.delta import compare_trees
32
35
from bzrlib.tree import EmptyTree, RevisionTree
33
 
        
34
 
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
 
36
from bzrlib.inventory import Inventory
 
37
from bzrlib.weavestore import WeaveStore
 
38
from bzrlib.store import ImmutableStore
 
39
import bzrlib.xml5
 
40
import bzrlib.ui
 
41
 
 
42
 
 
43
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
 
44
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
35
45
## TODO: Maybe include checks for common corruption of newlines, etc?
36
46
 
37
47
 
38
48
# TODO: Some operations like log might retrieve the same revisions
39
49
# repeatedly to calculate deltas.  We could perhaps have a weakref
40
 
# cache in memory to make this faster.
41
 
 
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
 
 
 
50
# cache in memory to make this faster.  In general anything can be
 
51
# cached in memory between lock and unlock operations.
 
52
 
 
53
def find_branch(*ignored, **ignored_too):
 
54
    # XXX: leave this here for about one release, then remove it
 
55
    raise NotImplementedError('find_branch() is not supported anymore, '
 
56
                              'please use one of the new branch constructors')
67
57
 
68
58
def _relpath(base, path):
69
59
    """Return path relative to base, or raise exception.
87
77
        if tail:
88
78
            s.insert(0, tail)
89
79
    else:
90
 
        from errors import NotBranchError
91
80
        raise NotBranchError("path %r is not within branch %r" % (rp, base))
92
81
 
93
82
    return os.sep.join(s)
101
90
    It is not necessary that f exists.
102
91
 
103
92
    Basically we keep looking up until we find the control directory or
104
 
    run into the root."""
 
93
    run into the root.  If there isn't one, raises NotBranchError.
 
94
    """
105
95
    if f == None:
106
96
        f = os.getcwd()
107
97
    elif hasattr(os.path, 'realpath'):
120
110
        head, tail = os.path.split(f)
121
111
        if head == f:
122
112
            # reached the root, whatever that may be
123
 
            raise BzrError('%r is not in a branch' % orig_f)
 
113
            raise NotBranchError('%s is not in a branch' % orig_f)
124
114
        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.")
 
115
 
 
116
 
131
117
 
132
118
 
133
119
######################################################################
137
123
    """Branch holding a history of revisions.
138
124
 
139
125
    base
140
 
        Base directory of the branch.
 
126
        Base directory/url of the branch.
 
127
    """
 
128
    base = None
 
129
 
 
130
    def __init__(self, *ignored, **ignored_too):
 
131
        raise NotImplementedError('The Branch class is abstract')
 
132
 
 
133
    @staticmethod
 
134
    def open(base):
 
135
        """Open an existing branch, rooted at 'base' (url)"""
 
136
        if base and (base.startswith('http://') or base.startswith('https://')):
 
137
            from bzrlib.remotebranch import RemoteBranch
 
138
            return RemoteBranch(base, find_root=False)
 
139
        else:
 
140
            return LocalBranch(base, find_root=False)
 
141
 
 
142
    @staticmethod
 
143
    def open_containing(url):
 
144
        """Open an existing branch which contains url.
 
145
        
 
146
        This probes for a branch at url, and searches upwards from there.
 
147
        """
 
148
        if url and (url.startswith('http://') or url.startswith('https://')):
 
149
            from bzrlib.remotebranch import RemoteBranch
 
150
            return RemoteBranch(url)
 
151
        else:
 
152
            return LocalBranch(url)
 
153
 
 
154
    @staticmethod
 
155
    def initialize(base):
 
156
        """Create a new branch, rooted at 'base' (url)"""
 
157
        if base and (base.startswith('http://') or base.startswith('https://')):
 
158
            from bzrlib.remotebranch import RemoteBranch
 
159
            return RemoteBranch(base, init=True)
 
160
        else:
 
161
            return LocalBranch(base, init=True)
 
162
 
 
163
    def setup_caching(self, cache_root):
 
164
        """Subclasses that care about caching should override this, and set
 
165
        up cached stores located under cache_root.
 
166
        """
 
167
 
 
168
 
 
169
class LocalBranch(Branch):
 
170
    """A branch stored in the actual filesystem.
 
171
 
 
172
    Note that it's "local" in the context of the filesystem; it doesn't
 
173
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
 
174
    it's writable, and can be accessed via the normal filesystem API.
141
175
 
142
176
    _lock_mode
143
177
        None, or 'r' or 'w'
149
183
    _lock
150
184
        Lock object from bzrlib.lock.
151
185
    """
152
 
    base = None
 
186
    # We actually expect this class to be somewhat short-lived; part of its
 
187
    # purpose is to try to isolate what bits of the branch logic are tied to
 
188
    # filesystem access, so that in a later step, we can extricate them to
 
189
    # a separarte ("storage") class.
153
190
    _lock_mode = None
154
191
    _lock_count = None
155
192
    _lock = None
 
193
    _inventory_weave = None
156
194
    
157
195
    # Map some sort of prefix into a namespace
158
196
    # stuff like "revno:10", "revid:", etc.
159
197
    # This should match a prefix with a function which accepts
160
198
    REVISION_NAMESPACES = {}
161
199
 
162
 
    def __init__(self, base, init=False, find_root=True):
 
200
    def __init__(self, base, init=False, find_root=True,
 
201
                 relax_version_check=False):
163
202
        """Create new branch object at a particular location.
164
203
 
165
 
        base -- Base directory for the branch.
 
204
        base -- Base directory for the branch. May be a file:// url.
166
205
        
167
206
        init -- If True, create new control files in a previously
168
207
             unversioned directory.  If False, the branch must already
171
210
        find_root -- If true and init is false, find the root of the
172
211
             existing branch containing base.
173
212
 
 
213
        relax_version_check -- If true, the usual check for the branch
 
214
            version is not applied.  This is intended only for
 
215
            upgrade/recovery type use; it's not guaranteed that
 
216
            all operations will work on old format branches.
 
217
 
174
218
        In the test suite, creation of new trees is tested using the
175
219
        `ScratchBranch` class.
176
220
        """
177
 
        from bzrlib.store import ImmutableStore
178
221
        if init:
179
222
            self.base = os.path.realpath(base)
180
223
            self._make_control()
181
224
        elif find_root:
182
225
            self.base = find_branch_root(base)
183
226
        else:
 
227
            if base.startswith("file://"):
 
228
                base = base[7:]
184
229
            self.base = os.path.realpath(base)
185
230
            if not isdir(self.controlfilename('.')):
186
 
                from errors import NotBranchError
187
 
                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()
191
 
 
192
 
        self.text_store = ImmutableStore(self.controlfilename('text-store'))
193
 
        self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
194
 
        self.inventory_store = ImmutableStore(self.controlfilename('inventory-store'))
 
231
                raise NotBranchError('not a bzr branch: %s' % quotefn(base),
 
232
                                     ['use "bzr init" to initialize a '
 
233
                                      'new working tree'])
 
234
        self._check_format(relax_version_check)
 
235
        cfn = self.controlfilename
 
236
        if self._branch_format == 4:
 
237
            self.inventory_store = ImmutableStore(cfn('inventory-store'))
 
238
            self.text_store = ImmutableStore(cfn('text-store'))
 
239
        elif self._branch_format == 5:
 
240
            self.control_weaves = WeaveStore(cfn([]))
 
241
            self.weave_store = WeaveStore(cfn('weaves'))
 
242
            if init:
 
243
                # FIXME: Unify with make_control_files
 
244
                self.control_weaves.put_empty_weave('inventory')
 
245
                self.control_weaves.put_empty_weave('ancestry')
 
246
        self.revision_store = ImmutableStore(cfn('revision-store'))
195
247
 
196
248
 
197
249
    def __str__(self):
203
255
 
204
256
    def __del__(self):
205
257
        if self._lock_mode or self._lock:
206
 
            from warnings import warn
 
258
            # XXX: This should show something every time, and be suitable for
 
259
            # headless operation and embedding
207
260
            warn("branch %r was not explicitly unlocked" % self)
208
261
            self._lock.unlock()
209
262
 
210
 
 
211
 
 
212
263
    def lock_write(self):
213
264
        if self._lock_mode:
214
265
            if self._lock_mode != 'w':
215
 
                from errors import LockError
216
266
                raise LockError("can't upgrade to a write lock from %r" %
217
267
                                self._lock_mode)
218
268
            self._lock_count += 1
224
274
            self._lock_count = 1
225
275
 
226
276
 
227
 
 
228
277
    def lock_read(self):
229
278
        if self._lock_mode:
230
279
            assert self._lock_mode in ('r', 'w'), \
237
286
            self._lock_mode = 'r'
238
287
            self._lock_count = 1
239
288
                        
240
 
 
241
 
            
242
289
    def unlock(self):
243
290
        if not self._lock_mode:
244
 
            from errors import LockError
245
291
            raise LockError('branch %r is not locked' % (self))
246
292
 
247
293
        if self._lock_count > 1:
251
297
            self._lock = None
252
298
            self._lock_mode = self._lock_count = None
253
299
 
254
 
 
255
300
    def abspath(self, name):
256
301
        """Return absolute filename for something in the branch"""
257
302
        return os.path.join(self.base, name)
258
303
 
259
 
 
260
304
    def relpath(self, path):
261
305
        """Return path relative to this branch of something inside it.
262
306
 
263
307
        Raises an error if path is not in this branch."""
264
308
        return _relpath(self.base, path)
265
309
 
266
 
 
267
310
    def controlfilename(self, file_or_path):
268
311
        """Return location relative to branch."""
269
312
        if isinstance(file_or_path, basestring):
296
339
        else:
297
340
            raise BzrError("invalid controlfile mode %r" % mode)
298
341
 
299
 
 
300
 
 
301
342
    def _make_control(self):
302
 
        from bzrlib.inventory import Inventory
303
 
        from bzrlib.xml import pack_xml
304
 
        
305
343
        os.mkdir(self.controlfilename([]))
306
344
        self.controlfile('README', 'w').write(
307
345
            "This is a Bazaar-NG control directory.\n"
308
346
            "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'):
 
347
        self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT_5)
 
348
        for d in ('text-store', 'revision-store',
 
349
                  'weaves'):
311
350
            os.mkdir(self.controlfilename(d))
312
 
        for f in ('revision-history', 'merged-patches',
313
 
                  'pending-merged-patches', 'branch-name',
 
351
        for f in ('revision-history',
 
352
                  'branch-name',
314
353
                  'branch-lock',
315
354
                  'pending-merges'):
316
355
            self.controlfile(f, 'w').write('')
317
356
        mutter('created control directory in ' + self.base)
318
357
 
319
 
        pack_xml(Inventory(gen_root_id()), self.controlfile('inventory','w'))
320
 
 
321
 
 
322
 
    def _check_format(self):
 
358
        # if we want per-tree root ids then this is the place to set
 
359
        # them; they're not needed for now and so ommitted for
 
360
        # simplicity.
 
361
        f = self.controlfile('inventory','w')
 
362
        bzrlib.xml5.serializer_v5.write_inventory(Inventory(), f)
 
363
 
 
364
 
 
365
    def _check_format(self, relax_version_check):
323
366
        """Check this branch format is supported.
324
367
 
325
 
        The current tool only supports the current unstable format.
 
368
        The format level is stored, as an integer, in
 
369
        self._branch_format for code that needs to check it later.
326
370
 
327
371
        In the future, we might need different in-memory Branch
328
372
        classes to support downlevel branches.  But not yet.
329
373
        """
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
 
        fmt = self.controlfile('branch-format', 'r').read()
334
 
        fmt.replace('\r\n', '')
335
 
        if fmt != BZR_BRANCH_FORMAT:
 
374
        try:
 
375
            fmt = self.controlfile('branch-format', 'r').read()
 
376
        except IOError, e:
 
377
            if e.errno == errno.ENOENT:
 
378
                raise NotBranchError(self.base)
 
379
            else:
 
380
                raise
 
381
 
 
382
        if fmt == BZR_BRANCH_FORMAT_5:
 
383
            self._branch_format = 5
 
384
        elif fmt == BZR_BRANCH_FORMAT_4:
 
385
            self._branch_format = 4
 
386
 
 
387
        if (not relax_version_check
 
388
            and self._branch_format != 5):
336
389
            raise BzrError('sorry, branch format %r not supported' % fmt,
337
390
                           ['use a different bzr version',
338
391
                            'or remove the .bzr directory and "bzr init" again'])
356
409
 
357
410
    def read_working_inventory(self):
358
411
        """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
412
        self.lock_read()
364
413
        try:
365
414
            # ElementTree does its own conversion from UTF-8, so open in
366
415
            # 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
 
416
            f = self.controlfile('inventory', 'rb')
 
417
            return bzrlib.xml5.serializer_v5.read_inventory(f)
372
418
        finally:
373
419
            self.unlock()
374
420
            
380
426
        will be committed to the next revision.
381
427
        """
382
428
        from bzrlib.atomicfile import AtomicFile
383
 
        from bzrlib.xml import pack_xml
384
429
        
385
430
        self.lock_write()
386
431
        try:
387
432
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
388
433
            try:
389
 
                pack_xml(inv, f)
 
434
                bzrlib.xml5.serializer_v5.write_inventory(inv, f)
390
435
                f.commit()
391
436
            finally:
392
437
                f.close()
400
445
                         """Inventory for the working copy.""")
401
446
 
402
447
 
403
 
    def add(self, files, verbose=False, ids=None):
 
448
    def add(self, files, ids=None):
404
449
        """Make files versioned.
405
450
 
406
 
        Note that the command line normally calls smart_add instead.
 
451
        Note that the command line normally calls smart_add instead,
 
452
        which can automatically recurse.
407
453
 
408
454
        This puts the files in the Added state, so that they will be
409
455
        recorded by the next commit.
419
465
        TODO: Perhaps have an option to add the ids even if the files do
420
466
              not (yet) exist.
421
467
 
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.
 
468
        TODO: Perhaps yield the ids and paths as they're added.
428
469
        """
429
470
        # TODO: Re-adding a file that is removed in the working copy
430
471
        # should probably put it back with the previous ID.
466
507
                    file_id = gen_file_id(f)
467
508
                inv.add_path(f, kind=kind, file_id=file_id)
468
509
 
469
 
                if verbose:
470
 
                    print 'added', quotefn(f)
471
 
 
472
510
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
473
511
 
474
512
            self._write_inventory(inv)
480
518
        """Print `file` to stdout."""
481
519
        self.lock_read()
482
520
        try:
483
 
            tree = self.revision_tree(self.lookup_revision(revno))
 
521
            tree = self.revision_tree(self.get_rev_id(revno))
484
522
            # use inventory as it was in that revision
485
523
            file_id = tree.inventory.path2id(file)
486
524
            if not file_id:
584
622
            f.close()
585
623
 
586
624
 
587
 
    def get_revision_xml(self, revision_id):
 
625
    def has_revision(self, revision_id):
 
626
        """True if this branch has a copy of the revision.
 
627
 
 
628
        This does not necessarily imply the revision is merge
 
629
        or on the mainline."""
 
630
        return (revision_id is None
 
631
                or revision_id in self.revision_store)
 
632
 
 
633
 
 
634
    def get_revision_xml_file(self, revision_id):
588
635
        """Return XML file object for revision object."""
589
636
        if not revision_id or not isinstance(revision_id, basestring):
590
637
            raise InvalidRevisionId(revision_id)
593
640
        try:
594
641
            try:
595
642
                return self.revision_store[revision_id]
596
 
            except IndexError:
597
 
                raise bzrlib.errors.NoSuchRevision(revision_id)
 
643
            except (IndexError, KeyError):
 
644
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
598
645
        finally:
599
646
            self.unlock()
600
647
 
601
648
 
 
649
    def get_revision_xml(self, revision_id):
 
650
        return self.get_revision_xml_file(revision_id).read()
 
651
 
 
652
 
602
653
    def get_revision(self, revision_id):
603
654
        """Return the Revision object for a named revision"""
604
 
        xml_file = self.get_revision_xml(revision_id)
 
655
        xml_file = self.get_revision_xml_file(revision_id)
605
656
 
606
657
        try:
607
 
            r = unpack_xml(Revision, xml_file)
 
658
            r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
608
659
        except SyntaxError, e:
609
660
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
610
661
                                         [revision_id,
635
686
 
636
687
        return compare_trees(old_tree, new_tree)
637
688
 
638
 
        
639
689
 
640
690
    def get_revision_sha1(self, revision_id):
641
691
        """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):
 
692
        return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
 
693
 
 
694
 
 
695
    def _get_ancestry_weave(self):
 
696
        return self.control_weaves.get_weave('ancestry')
 
697
        
 
698
 
 
699
    def get_ancestry(self, revision_id):
 
700
        """Return a list of revision-ids integrated by a revision.
 
701
        """
 
702
        # strip newlines
 
703
        if revision_id is None:
 
704
            return [None]
 
705
        w = self._get_ancestry_weave()
 
706
        return [None] + [l[:-1] for l in w.get_iter(w.lookup(revision_id))]
 
707
 
 
708
 
 
709
    def get_inventory_weave(self):
 
710
        return self.control_weaves.get_weave('inventory')
 
711
 
 
712
 
 
713
    def get_inventory(self, revision_id):
 
714
        """Get Inventory object by hash."""
 
715
        xml = self.get_inventory_xml(revision_id)
 
716
        return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
 
717
 
 
718
 
 
719
    def get_inventory_xml(self, revision_id):
 
720
        """Get inventory XML as a file object."""
 
721
        try:
 
722
            assert isinstance(revision_id, basestring), type(revision_id)
 
723
            iw = self.get_inventory_weave()
 
724
            return iw.get_text(iw.lookup(revision_id))
 
725
        except IndexError:
 
726
            raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
 
727
 
 
728
 
 
729
    def get_inventory_sha1(self, revision_id):
664
730
        """Return the sha1 hash of the inventory entry
665
731
        """
666
 
        return sha_file(self.inventory_store[inventory_id])
 
732
        return self.get_revision(revision_id).inventory_sha1
667
733
 
668
734
 
669
735
    def get_revision_inventory(self, revision_id):
670
736
        """Return inventory of a past revision."""
671
 
        # bzr 0.0.6 imposes the constraint that the inventory_id
 
737
        # TODO: Unify this with get_inventory()
 
738
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
672
739
        # must be the same as its revision, so this is trivial.
673
740
        if revision_id == None:
674
 
            from bzrlib.inventory import Inventory
675
741
            return Inventory(self.get_root_id())
676
742
        else:
677
743
            return self.get_inventory(revision_id)
678
744
 
679
745
 
680
746
    def revision_history(self):
681
 
        """Return sequence of revision hashes on to this branch.
682
 
 
683
 
        >>> ScratchBranch().revision_history()
684
 
        []
685
 
        """
 
747
        """Return sequence of revision hashes on to this branch."""
686
748
        self.lock_read()
687
749
        try:
688
750
            return [l.rstrip('\r\n') for l in
693
755
 
694
756
    def common_ancestor(self, other, self_revno=None, other_revno=None):
695
757
        """
696
 
        >>> import commit
 
758
        >>> from bzrlib.commit import commit
697
759
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
698
760
        >>> sb.common_ancestor(sb) == (None, None)
699
761
        True
700
 
        >>> commit.commit(sb, "Committing first revision", verbose=False)
 
762
        >>> commit(sb, "Committing first revision", verbose=False)
701
763
        >>> sb.common_ancestor(sb)[0]
702
764
        1
703
765
        >>> clone = sb.clone()
704
 
        >>> commit.commit(sb, "Committing second revision", verbose=False)
 
766
        >>> commit(sb, "Committing second revision", verbose=False)
705
767
        >>> sb.common_ancestor(sb)[0]
706
768
        2
707
769
        >>> sb.common_ancestor(clone)[0]
708
770
        1
709
 
        >>> commit.commit(clone, "Committing divergent second revision", 
 
771
        >>> commit(clone, "Committing divergent second revision", 
710
772
        ...               verbose=False)
711
773
        >>> sb.common_ancestor(clone)[0]
712
774
        1
745
807
        return len(self.revision_history())
746
808
 
747
809
 
748
 
    def last_patch(self):
 
810
    def last_revision(self):
749
811
        """Return last patch hash, or None if no history.
750
812
        """
751
813
        ph = self.revision_history()
755
817
            return None
756
818
 
757
819
 
758
 
    def missing_revisions(self, other, stop_revision=None):
759
 
        """
 
820
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
 
821
        """Return a list of new revisions that would perfectly fit.
 
822
        
760
823
        If self and other have not diverged, return a list of the revisions
761
824
        present in other, but missing from self.
762
825
 
782
845
        Traceback (most recent call last):
783
846
        DivergedBranches: These branches have diverged.
784
847
        """
 
848
        # FIXME: If the branches have diverged, but the latest
 
849
        # revision in this branch is completely merged into the other,
 
850
        # then we should still be able to pull.
785
851
        self_history = self.revision_history()
786
852
        self_len = len(self_history)
787
853
        other_history = other.revision_history()
793
859
 
794
860
        if stop_revision is None:
795
861
            stop_revision = other_len
796
 
        elif stop_revision > other_len:
797
 
            raise NoSuchRevision(self, stop_revision)
798
 
        
 
862
        else:
 
863
            assert isinstance(stop_revision, int)
 
864
            if stop_revision > other_len:
 
865
                raise bzrlib.errors.NoSuchRevision(self, stop_revision)
799
866
        return other_history[self_len:stop_revision]
800
867
 
801
 
 
802
868
    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
824
 
        """
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
 
        
 
869
        """Pull in new perfect-fit revisions."""
 
870
        from bzrlib.fetch import greedy_fetch
 
871
        from bzrlib.revision import get_intervening_revisions
 
872
        if stop_revision is None:
 
873
            stop_revision = other.last_revision()
 
874
        greedy_fetch(to_branch=self, from_branch=other,
 
875
                     revision=stop_revision)
 
876
        pullable_revs = self.missing_revisions(
 
877
            other, other.revision_id_to_revno(stop_revision))
 
878
        if pullable_revs:
 
879
            greedy_fetch(to_branch=self,
 
880
                         from_branch=other,
 
881
                         revision=pullable_revs[-1])
 
882
            self.append_revision(*pullable_revs)
 
883
    
870
884
    def commit(self, *args, **kw):
871
 
        from bzrlib.commit import commit
872
 
        commit(self, *args, **kw)
873
 
        
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
 
885
        from bzrlib.commit import Commit
 
886
        Commit().commit(self, *args, **kw)
 
887
    
 
888
    def revision_id_to_revno(self, revision_id):
 
889
        """Given a revision id, return its revno"""
 
890
        if revision_id is None:
 
891
            return 0
 
892
        history = self.revision_history()
 
893
        try:
 
894
            return history.index(revision_id) + 1
 
895
        except ValueError:
 
896
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
897
 
 
898
    def get_rev_id(self, revno, history=None):
 
899
        """Find the revision id of the specified revno."""
 
900
        if revno == 0:
 
901
            return None
 
902
        if history is None:
 
903
            history = self.revision_history()
 
904
        elif revno <= 0 or revno > len(history):
 
905
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
906
        return history[revno - 1]
1032
907
 
1033
908
    def revision_tree(self, revision_id):
1034
909
        """Return Tree for a revision on this branch.
1041
916
            return EmptyTree()
1042
917
        else:
1043
918
            inv = self.get_revision_inventory(revision_id)
1044
 
            return RevisionTree(self.text_store, inv)
 
919
            return RevisionTree(self.weave_store, inv, revision_id)
1045
920
 
1046
921
 
1047
922
    def working_tree(self):
1048
923
        """Return a `Tree` for the working copy."""
1049
 
        from workingtree import WorkingTree
 
924
        from bzrlib.workingtree import WorkingTree
1050
925
        return WorkingTree(self.base, self.read_working_inventory())
1051
926
 
1052
927
 
1055
930
 
1056
931
        If there are no revisions yet, return an `EmptyTree`.
1057
932
        """
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
 
 
 
933
        return self.revision_tree(self.last_revision())
1064
934
 
1065
935
 
1066
936
    def rename_one(self, from_rel, to_rel):
1098
968
 
1099
969
            inv.rename(file_id, to_dir_id, to_tail)
1100
970
 
1101
 
            print "%s => %s" % (from_rel, to_rel)
1102
 
 
1103
971
            from_abs = self.abspath(from_rel)
1104
972
            to_abs = self.abspath(to_rel)
1105
973
            try:
1106
 
                os.rename(from_abs, to_abs)
 
974
                rename(from_abs, to_abs)
1107
975
            except OSError, e:
1108
976
                raise BzrError("failed to rename %r to %r: %s"
1109
977
                        % (from_abs, to_abs, e[1]),
1124
992
 
1125
993
        Note that to_name is only the last component of the new name;
1126
994
        this doesn't change the directory.
 
995
 
 
996
        This returns a list of (from_path, to_path) pairs for each
 
997
        entry that is moved.
1127
998
        """
 
999
        result = []
1128
1000
        self.lock_write()
1129
1001
        try:
1130
1002
            ## TODO: Option to move IDs only
1165
1037
            for f in from_paths:
1166
1038
                name_tail = splitpath(f)[-1]
1167
1039
                dest_path = appendpath(to_name, name_tail)
1168
 
                print "%s => %s" % (f, dest_path)
 
1040
                result.append((f, dest_path))
1169
1041
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1170
1042
                try:
1171
 
                    os.rename(self.abspath(f), self.abspath(dest_path))
 
1043
                    rename(self.abspath(f), self.abspath(dest_path))
1172
1044
                except OSError, e:
1173
1045
                    raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1174
1046
                            ["rename rolled back"])
1177
1049
        finally:
1178
1050
            self.unlock()
1179
1051
 
 
1052
        return result
 
1053
 
1180
1054
 
1181
1055
    def revert(self, filenames, old_tree=None, backups=True):
1182
1056
        """Restore selected files to the versions from a previous tree.
1238
1112
 
1239
1113
 
1240
1114
    def add_pending_merge(self, revision_id):
1241
 
        from bzrlib.revision import validate_revision_id
1242
 
 
1243
1115
        validate_revision_id(revision_id)
1244
 
 
 
1116
        # TODO: Perhaps should check at this point that the
 
1117
        # history of the revision is actually present?
1245
1118
        p = self.pending_merges()
1246
1119
        if revision_id in p:
1247
1120
            return
1264
1137
            self.unlock()
1265
1138
 
1266
1139
 
1267
 
 
1268
 
class ScratchBranch(Branch):
 
1140
    def get_parent(self):
 
1141
        """Return the parent location of the branch.
 
1142
 
 
1143
        This is the default location for push/pull/missing.  The usual
 
1144
        pattern is that the user can override it by specifying a
 
1145
        location.
 
1146
        """
 
1147
        import errno
 
1148
        _locs = ['parent', 'pull', 'x-pull']
 
1149
        for l in _locs:
 
1150
            try:
 
1151
                return self.controlfile(l, 'r').read().strip('\n')
 
1152
            except IOError, e:
 
1153
                if e.errno != errno.ENOENT:
 
1154
                    raise
 
1155
        return None
 
1156
 
 
1157
 
 
1158
    def set_parent(self, url):
 
1159
        # TODO: Maybe delete old location files?
 
1160
        from bzrlib.atomicfile import AtomicFile
 
1161
        self.lock_write()
 
1162
        try:
 
1163
            f = AtomicFile(self.controlfilename('parent'))
 
1164
            try:
 
1165
                f.write(url + '\n')
 
1166
                f.commit()
 
1167
            finally:
 
1168
                f.close()
 
1169
        finally:
 
1170
            self.unlock()
 
1171
 
 
1172
    def check_revno(self, revno):
 
1173
        """\
 
1174
        Check whether a revno corresponds to any revision.
 
1175
        Zero (the NULL revision) is considered valid.
 
1176
        """
 
1177
        if revno != 0:
 
1178
            self.check_real_revno(revno)
 
1179
            
 
1180
    def check_real_revno(self, revno):
 
1181
        """\
 
1182
        Check whether a revno corresponds to a real revision.
 
1183
        Zero (the NULL revision) is considered invalid
 
1184
        """
 
1185
        if revno < 1 or revno > self.revno():
 
1186
            raise InvalidRevisionNumber(revno)
 
1187
        
 
1188
        
 
1189
        
 
1190
 
 
1191
 
 
1192
class ScratchBranch(LocalBranch):
1269
1193
    """Special test class: a branch that cleans up after itself.
1270
1194
 
1271
1195
    >>> b = ScratchBranch()
1288
1212
        if base is None:
1289
1213
            base = mkdtemp()
1290
1214
            init = True
1291
 
        Branch.__init__(self, base, init=init)
 
1215
        LocalBranch.__init__(self, base, init=init)
1292
1216
        for d in dirs:
1293
1217
            os.mkdir(self.abspath(d))
1294
1218
            
1300
1224
        """
1301
1225
        >>> orig = ScratchBranch(files=["file1", "file2"])
1302
1226
        >>> clone = orig.clone()
1303
 
        >>> os.path.samefile(orig.base, clone.base)
 
1227
        >>> if os.name != 'nt':
 
1228
        ...   os.path.samefile(orig.base, clone.base)
 
1229
        ... else:
 
1230
        ...   orig.base == clone.base
 
1231
        ...
1304
1232
        False
1305
1233
        >>> os.path.isfile(os.path.join(clone.base, "file1"))
1306
1234
        True
1311
1239
        os.rmdir(base)
1312
1240
        copytree(self.base, base, symlinks=True)
1313
1241
        return ScratchBranch(base=base)
 
1242
 
 
1243
 
1314
1244
        
1315
1245
    def __del__(self):
1316
1246
        self.destroy()
1386
1316
    """Return a new tree-root file id."""
1387
1317
    return gen_file_id('TREE_ROOT')
1388
1318
 
 
1319
 
 
1320
def copy_branch(branch_from, to_location, revision=None):
 
1321
    """Copy branch_from into the existing directory to_location.
 
1322
 
 
1323
    revision
 
1324
        If not None, only revisions up to this point will be copied.
 
1325
        The head of the new branch will be that revision.  Must be a
 
1326
        revid or None.
 
1327
 
 
1328
    to_location
 
1329
        The name of a local directory that exists but is empty.
 
1330
    """
 
1331
    # TODO: This could be done *much* more efficiently by just copying
 
1332
    # all the whole weaves and revisions, rather than getting one
 
1333
    # revision at a time.
 
1334
    from bzrlib.merge import merge
 
1335
 
 
1336
    assert isinstance(branch_from, Branch)
 
1337
    assert isinstance(to_location, basestring)
 
1338
    
 
1339
    br_to = Branch.initialize(to_location)
 
1340
    br_to.set_root_id(branch_from.get_root_id())
 
1341
    if revision is None:
 
1342
        revision = branch_from.last_revision()
 
1343
    br_to.update_revisions(branch_from, stop_revision=revision)
 
1344
    merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
1345
          check_clean=False, ignore_zero=True)
 
1346
    br_to.set_parent(branch_from.base)
 
1347
    return br_to