/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2005-09-29 12:49:59 UTC
  • mto: (1185.14.2)
  • mto: This revision was merged to the branch mainline in revision 1396.
  • Revision ID: mbp@sourcefrog.net-20050929124959-df3f175844fc90ed
- remove redundant import

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, UnlistableStore,
 
32
                           UnlistableBranch)
28
33
from bzrlib.textui import show_status
29
 
from bzrlib.revision import Revision
30
 
from bzrlib.xml import unpack_xml
 
34
from bzrlib.revision import Revision, validate_revision_id, is_ancestor
31
35
from bzrlib.delta import compare_trees
32
36
from bzrlib.tree import EmptyTree, RevisionTree
33
 
        
34
 
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
 
37
from bzrlib.inventory import Inventory
 
38
from bzrlib.weavestore import WeaveStore
 
39
from bzrlib.store import copy_all, ImmutableStore
 
40
import bzrlib.xml5
 
41
import bzrlib.ui
 
42
 
 
43
 
 
44
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
 
45
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
35
46
## TODO: Maybe include checks for common corruption of newlines, etc?
36
47
 
37
48
 
38
49
# TODO: Some operations like log might retrieve the same revisions
39
50
# 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
 
 
 
51
# cache in memory to make this faster.  In general anything can be
 
52
# cached in memory between lock and unlock operations.
 
53
 
 
54
def find_branch(*ignored, **ignored_too):
 
55
    # XXX: leave this here for about one release, then remove it
 
56
    raise NotImplementedError('find_branch() is not supported anymore, '
 
57
                              'please use one of the new branch constructors')
67
58
 
68
59
def _relpath(base, path):
69
60
    """Return path relative to base, or raise exception.
87
78
        if tail:
88
79
            s.insert(0, tail)
89
80
    else:
90
 
        from errors import NotBranchError
91
81
        raise NotBranchError("path %r is not within branch %r" % (rp, base))
92
82
 
93
83
    return os.sep.join(s)
101
91
    It is not necessary that f exists.
102
92
 
103
93
    Basically we keep looking up until we find the control directory or
104
 
    run into the root."""
 
94
    run into the root.  If there isn't one, raises NotBranchError.
 
95
    """
105
96
    if f == None:
106
97
        f = os.getcwd()
107
98
    elif hasattr(os.path, 'realpath'):
120
111
        head, tail = os.path.split(f)
121
112
        if head == f:
122
113
            # reached the root, whatever that may be
123
 
            raise BzrError('%r is not in a branch' % orig_f)
 
114
            raise NotBranchError('%s is not in a branch' % orig_f)
124
115
        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.")
 
116
 
 
117
 
131
118
 
132
119
 
133
120
######################################################################
137
124
    """Branch holding a history of revisions.
138
125
 
139
126
    base
140
 
        Base directory of the branch.
 
127
        Base directory/url of the branch.
 
128
    """
 
129
    base = None
 
130
 
 
131
    def __init__(self, *ignored, **ignored_too):
 
132
        raise NotImplementedError('The Branch class is abstract')
 
133
 
 
134
    @staticmethod
 
135
    def open_downlevel(base):
 
136
        """Open a branch which may be of an old format.
 
137
        
 
138
        Only local branches are supported."""
 
139
        return LocalBranch(base, find_root=False, relax_version_check=True)
 
140
        
 
141
    @staticmethod
 
142
    def open(base):
 
143
        """Open an existing branch, rooted at 'base' (url)"""
 
144
        if base and (base.startswith('http://') or base.startswith('https://')):
 
145
            from bzrlib.remotebranch import RemoteBranch
 
146
            return RemoteBranch(base, find_root=False)
 
147
        else:
 
148
            return LocalBranch(base, find_root=False)
 
149
 
 
150
    @staticmethod
 
151
    def open_containing(url):
 
152
        """Open an existing branch which contains url.
 
153
        
 
154
        This probes for a branch at url, and searches upwards from there.
 
155
        """
 
156
        if url and (url.startswith('http://') or url.startswith('https://')):
 
157
            from bzrlib.remotebranch import RemoteBranch
 
158
            return RemoteBranch(url)
 
159
        else:
 
160
            return LocalBranch(url)
 
161
 
 
162
    @staticmethod
 
163
    def initialize(base):
 
164
        """Create a new branch, rooted at 'base' (url)"""
 
165
        if base and (base.startswith('http://') or base.startswith('https://')):
 
166
            from bzrlib.remotebranch import RemoteBranch
 
167
            return RemoteBranch(base, init=True)
 
168
        else:
 
169
            return LocalBranch(base, init=True)
 
170
 
 
171
    def setup_caching(self, cache_root):
 
172
        """Subclasses that care about caching should override this, and set
 
173
        up cached stores located under cache_root.
 
174
        """
 
175
 
 
176
 
 
177
class LocalBranch(Branch):
 
178
    """A branch stored in the actual filesystem.
 
179
 
 
180
    Note that it's "local" in the context of the filesystem; it doesn't
 
181
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
 
182
    it's writable, and can be accessed via the normal filesystem API.
141
183
 
142
184
    _lock_mode
143
185
        None, or 'r' or 'w'
149
191
    _lock
150
192
        Lock object from bzrlib.lock.
151
193
    """
152
 
    base = None
 
194
    # We actually expect this class to be somewhat short-lived; part of its
 
195
    # purpose is to try to isolate what bits of the branch logic are tied to
 
196
    # filesystem access, so that in a later step, we can extricate them to
 
197
    # a separarte ("storage") class.
153
198
    _lock_mode = None
154
199
    _lock_count = None
155
200
    _lock = None
 
201
    _inventory_weave = None
156
202
    
157
203
    # Map some sort of prefix into a namespace
158
204
    # stuff like "revno:10", "revid:", etc.
159
205
    # This should match a prefix with a function which accepts
160
206
    REVISION_NAMESPACES = {}
161
207
 
162
 
    def __init__(self, base, init=False, find_root=True):
 
208
    def push_stores(self, branch_to):
 
209
        """Copy the content of this branches store to branch_to."""
 
210
        if (self._branch_format != branch_to._branch_format
 
211
            or self._branch_format != 4):
 
212
            from bzrlib.fetch import greedy_fetch
 
213
            mutter("falling back to fetch logic to push between %s(%s) and %s(%s)",
 
214
                   self, self._branch_format, branch_to, branch_to._branch_format)
 
215
            greedy_fetch(to_branch=branch_to, from_branch=self,
 
216
                         revision=self.last_revision())
 
217
            return
 
218
 
 
219
        store_pairs = ((self.text_store,      branch_to.text_store),
 
220
                       (self.inventory_store, branch_to.inventory_store),
 
221
                       (self.revision_store,  branch_to.revision_store))
 
222
        try:
 
223
            for from_store, to_store in store_pairs: 
 
224
                copy_all(from_store, to_store)
 
225
        except UnlistableStore:
 
226
            raise UnlistableBranch(from_store)
 
227
 
 
228
    def __init__(self, base, init=False, find_root=True,
 
229
                 relax_version_check=False):
163
230
        """Create new branch object at a particular location.
164
231
 
165
 
        base -- Base directory for the branch.
 
232
        base -- Base directory for the branch. May be a file:// url.
166
233
        
167
234
        init -- If True, create new control files in a previously
168
235
             unversioned directory.  If False, the branch must already
171
238
        find_root -- If true and init is false, find the root of the
172
239
             existing branch containing base.
173
240
 
 
241
        relax_version_check -- If true, the usual check for the branch
 
242
            version is not applied.  This is intended only for
 
243
            upgrade/recovery type use; it's not guaranteed that
 
244
            all operations will work on old format branches.
 
245
 
174
246
        In the test suite, creation of new trees is tested using the
175
247
        `ScratchBranch` class.
176
248
        """
177
 
        from bzrlib.store import ImmutableStore
178
249
        if init:
179
250
            self.base = os.path.realpath(base)
180
251
            self._make_control()
181
252
        elif find_root:
182
253
            self.base = find_branch_root(base)
183
254
        else:
 
255
            if base.startswith("file://"):
 
256
                base = base[7:]
184
257
            self.base = os.path.realpath(base)
185
258
            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'))
 
259
                raise NotBranchError('not a bzr branch: %s' % quotefn(base),
 
260
                                     ['use "bzr init" to initialize a '
 
261
                                      'new working tree'])
 
262
        self._check_format(relax_version_check)
 
263
        cfn = self.controlfilename
 
264
        if self._branch_format == 4:
 
265
            self.inventory_store = ImmutableStore(cfn('inventory-store'))
 
266
            self.text_store = ImmutableStore(cfn('text-store'))
 
267
        elif self._branch_format == 5:
 
268
            self.control_weaves = WeaveStore(cfn([]))
 
269
            self.weave_store = WeaveStore(cfn('weaves'))
 
270
            if init:
 
271
                # FIXME: Unify with make_control_files
 
272
                self.control_weaves.put_empty_weave('inventory')
 
273
                self.control_weaves.put_empty_weave('ancestry')
 
274
        self.revision_store = ImmutableStore(cfn('revision-store'))
195
275
 
196
276
 
197
277
    def __str__(self):
203
283
 
204
284
    def __del__(self):
205
285
        if self._lock_mode or self._lock:
206
 
            from warnings import warn
 
286
            # XXX: This should show something every time, and be suitable for
 
287
            # headless operation and embedding
207
288
            warn("branch %r was not explicitly unlocked" % self)
208
289
            self._lock.unlock()
209
290
 
210
 
 
211
 
 
212
291
    def lock_write(self):
213
292
        if self._lock_mode:
214
293
            if self._lock_mode != 'w':
215
 
                from errors import LockError
216
294
                raise LockError("can't upgrade to a write lock from %r" %
217
295
                                self._lock_mode)
218
296
            self._lock_count += 1
224
302
            self._lock_count = 1
225
303
 
226
304
 
227
 
 
228
305
    def lock_read(self):
229
306
        if self._lock_mode:
230
307
            assert self._lock_mode in ('r', 'w'), \
237
314
            self._lock_mode = 'r'
238
315
            self._lock_count = 1
239
316
                        
240
 
 
241
 
            
242
317
    def unlock(self):
243
318
        if not self._lock_mode:
244
 
            from errors import LockError
245
319
            raise LockError('branch %r is not locked' % (self))
246
320
 
247
321
        if self._lock_count > 1:
251
325
            self._lock = None
252
326
            self._lock_mode = self._lock_count = None
253
327
 
254
 
 
255
328
    def abspath(self, name):
256
329
        """Return absolute filename for something in the branch"""
257
330
        return os.path.join(self.base, name)
258
331
 
259
 
 
260
332
    def relpath(self, path):
261
333
        """Return path relative to this branch of something inside it.
262
334
 
263
335
        Raises an error if path is not in this branch."""
264
336
        return _relpath(self.base, path)
265
337
 
266
 
 
267
338
    def controlfilename(self, file_or_path):
268
339
        """Return location relative to branch."""
269
340
        if isinstance(file_or_path, basestring):
296
367
        else:
297
368
            raise BzrError("invalid controlfile mode %r" % mode)
298
369
 
299
 
 
300
 
 
301
370
    def _make_control(self):
302
 
        from bzrlib.inventory import Inventory
303
 
        from bzrlib.xml import pack_xml
304
 
        
305
371
        os.mkdir(self.controlfilename([]))
306
372
        self.controlfile('README', 'w').write(
307
373
            "This is a Bazaar-NG control directory.\n"
308
374
            "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'):
 
375
        self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT_5)
 
376
        for d in ('text-store', 'revision-store',
 
377
                  'weaves'):
311
378
            os.mkdir(self.controlfilename(d))
312
 
        for f in ('revision-history', 'merged-patches',
313
 
                  'pending-merged-patches', 'branch-name',
 
379
        for f in ('revision-history',
 
380
                  'branch-name',
314
381
                  'branch-lock',
315
382
                  'pending-merges'):
316
383
            self.controlfile(f, 'w').write('')
317
384
        mutter('created control directory in ' + self.base)
318
385
 
319
 
        pack_xml(Inventory(gen_root_id()), self.controlfile('inventory','w'))
320
 
 
321
 
 
322
 
    def _check_format(self):
 
386
        # if we want per-tree root ids then this is the place to set
 
387
        # them; they're not needed for now and so ommitted for
 
388
        # simplicity.
 
389
        f = self.controlfile('inventory','w')
 
390
        bzrlib.xml5.serializer_v5.write_inventory(Inventory(), f)
 
391
 
 
392
 
 
393
    def _check_format(self, relax_version_check):
323
394
        """Check this branch format is supported.
324
395
 
325
 
        The current tool only supports the current unstable format.
 
396
        The format level is stored, as an integer, in
 
397
        self._branch_format for code that needs to check it later.
326
398
 
327
399
        In the future, we might need different in-memory Branch
328
400
        classes to support downlevel branches.  But not yet.
329
401
        """
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:
 
402
        try:
 
403
            fmt = self.controlfile('branch-format', 'r').read()
 
404
        except IOError, e:
 
405
            if e.errno == errno.ENOENT:
 
406
                raise NotBranchError(self.base)
 
407
            else:
 
408
                raise
 
409
 
 
410
        if fmt == BZR_BRANCH_FORMAT_5:
 
411
            self._branch_format = 5
 
412
        elif fmt == BZR_BRANCH_FORMAT_4:
 
413
            self._branch_format = 4
 
414
 
 
415
        if (not relax_version_check
 
416
            and self._branch_format != 5):
336
417
            raise BzrError('sorry, branch format %r not supported' % fmt,
337
418
                           ['use a different bzr version',
338
419
                            'or remove the .bzr directory and "bzr init" again'])
356
437
 
357
438
    def read_working_inventory(self):
358
439
        """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
440
        self.lock_read()
364
441
        try:
365
442
            # ElementTree does its own conversion from UTF-8, so open in
366
443
            # 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
 
444
            f = self.controlfile('inventory', 'rb')
 
445
            return bzrlib.xml5.serializer_v5.read_inventory(f)
372
446
        finally:
373
447
            self.unlock()
374
448
            
380
454
        will be committed to the next revision.
381
455
        """
382
456
        from bzrlib.atomicfile import AtomicFile
383
 
        from bzrlib.xml import pack_xml
384
457
        
385
458
        self.lock_write()
386
459
        try:
387
460
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
388
461
            try:
389
 
                pack_xml(inv, f)
 
462
                bzrlib.xml5.serializer_v5.write_inventory(inv, f)
390
463
                f.commit()
391
464
            finally:
392
465
                f.close()
400
473
                         """Inventory for the working copy.""")
401
474
 
402
475
 
403
 
    def add(self, files, verbose=False, ids=None):
 
476
    def add(self, files, ids=None):
404
477
        """Make files versioned.
405
478
 
406
 
        Note that the command line normally calls smart_add instead.
 
479
        Note that the command line normally calls smart_add instead,
 
480
        which can automatically recurse.
407
481
 
408
482
        This puts the files in the Added state, so that they will be
409
483
        recorded by the next commit.
419
493
        TODO: Perhaps have an option to add the ids even if the files do
420
494
              not (yet) exist.
421
495
 
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.
 
496
        TODO: Perhaps yield the ids and paths as they're added.
428
497
        """
429
498
        # TODO: Re-adding a file that is removed in the working copy
430
499
        # should probably put it back with the previous ID.
466
535
                    file_id = gen_file_id(f)
467
536
                inv.add_path(f, kind=kind, file_id=file_id)
468
537
 
469
 
                if verbose:
470
 
                    print 'added', quotefn(f)
471
 
 
472
538
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
473
539
 
474
540
            self._write_inventory(inv)
480
546
        """Print `file` to stdout."""
481
547
        self.lock_read()
482
548
        try:
483
 
            tree = self.revision_tree(self.lookup_revision(revno))
 
549
            tree = self.revision_tree(self.get_rev_id(revno))
484
550
            # use inventory as it was in that revision
485
551
            file_id = tree.inventory.path2id(file)
486
552
            if not file_id:
584
650
            f.close()
585
651
 
586
652
 
587
 
    def get_revision_xml(self, revision_id):
 
653
    def has_revision(self, revision_id):
 
654
        """True if this branch has a copy of the revision.
 
655
 
 
656
        This does not necessarily imply the revision is merge
 
657
        or on the mainline."""
 
658
        return (revision_id is None
 
659
                or revision_id in self.revision_store)
 
660
 
 
661
 
 
662
    def get_revision_xml_file(self, revision_id):
588
663
        """Return XML file object for revision object."""
589
664
        if not revision_id or not isinstance(revision_id, basestring):
590
665
            raise InvalidRevisionId(revision_id)
593
668
        try:
594
669
            try:
595
670
                return self.revision_store[revision_id]
596
 
            except IndexError:
597
 
                raise bzrlib.errors.NoSuchRevision(revision_id)
 
671
            except (IndexError, KeyError):
 
672
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
598
673
        finally:
599
674
            self.unlock()
600
675
 
601
676
 
 
677
    def get_revision_xml(self, revision_id):
 
678
        return self.get_revision_xml_file(revision_id).read()
 
679
 
 
680
 
602
681
    def get_revision(self, revision_id):
603
682
        """Return the Revision object for a named revision"""
604
 
        xml_file = self.get_revision_xml(revision_id)
 
683
        xml_file = self.get_revision_xml_file(revision_id)
605
684
 
606
685
        try:
607
 
            r = unpack_xml(Revision, xml_file)
 
686
            r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
608
687
        except SyntaxError, e:
609
688
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
610
689
                                         [revision_id,
635
714
 
636
715
        return compare_trees(old_tree, new_tree)
637
716
 
638
 
        
639
717
 
640
718
    def get_revision_sha1(self, revision_id):
641
719
        """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):
 
720
        return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
 
721
 
 
722
 
 
723
    def _get_ancestry_weave(self):
 
724
        return self.control_weaves.get_weave('ancestry')
 
725
        
 
726
 
 
727
    def get_ancestry(self, revision_id):
 
728
        """Return a list of revision-ids integrated by a revision.
 
729
        """
 
730
        # strip newlines
 
731
        if revision_id is None:
 
732
            return [None]
 
733
        w = self._get_ancestry_weave()
 
734
        return [None] + [l[:-1] for l in w.get_iter(w.lookup(revision_id))]
 
735
 
 
736
 
 
737
    def get_inventory_weave(self):
 
738
        return self.control_weaves.get_weave('inventory')
 
739
 
 
740
 
 
741
    def get_inventory(self, revision_id):
 
742
        """Get Inventory object by hash."""
 
743
        xml = self.get_inventory_xml(revision_id)
 
744
        return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
 
745
 
 
746
 
 
747
    def get_inventory_xml(self, revision_id):
 
748
        """Get inventory XML as a file object."""
 
749
        try:
 
750
            assert isinstance(revision_id, basestring), type(revision_id)
 
751
            iw = self.get_inventory_weave()
 
752
            return iw.get_text(iw.lookup(revision_id))
 
753
        except IndexError:
 
754
            raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
 
755
 
 
756
 
 
757
    def get_inventory_sha1(self, revision_id):
664
758
        """Return the sha1 hash of the inventory entry
665
759
        """
666
 
        return sha_file(self.inventory_store[inventory_id])
 
760
        return self.get_revision(revision_id).inventory_sha1
667
761
 
668
762
 
669
763
    def get_revision_inventory(self, revision_id):
670
764
        """Return inventory of a past revision."""
671
 
        # bzr 0.0.6 imposes the constraint that the inventory_id
 
765
        # TODO: Unify this with get_inventory()
 
766
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
672
767
        # must be the same as its revision, so this is trivial.
673
768
        if revision_id == None:
674
 
            from bzrlib.inventory import Inventory
675
769
            return Inventory(self.get_root_id())
676
770
        else:
677
771
            return self.get_inventory(revision_id)
678
772
 
679
773
 
680
774
    def revision_history(self):
681
 
        """Return sequence of revision hashes on to this branch.
682
 
 
683
 
        >>> ScratchBranch().revision_history()
684
 
        []
685
 
        """
 
775
        """Return sequence of revision hashes on to this branch."""
686
776
        self.lock_read()
687
777
        try:
688
778
            return [l.rstrip('\r\n') for l in
693
783
 
694
784
    def common_ancestor(self, other, self_revno=None, other_revno=None):
695
785
        """
696
 
        >>> import commit
 
786
        >>> from bzrlib.commit import commit
697
787
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
698
788
        >>> sb.common_ancestor(sb) == (None, None)
699
789
        True
700
 
        >>> commit.commit(sb, "Committing first revision", verbose=False)
 
790
        >>> commit(sb, "Committing first revision", verbose=False)
701
791
        >>> sb.common_ancestor(sb)[0]
702
792
        1
703
793
        >>> clone = sb.clone()
704
 
        >>> commit.commit(sb, "Committing second revision", verbose=False)
 
794
        >>> commit(sb, "Committing second revision", verbose=False)
705
795
        >>> sb.common_ancestor(sb)[0]
706
796
        2
707
797
        >>> sb.common_ancestor(clone)[0]
708
798
        1
709
 
        >>> commit.commit(clone, "Committing divergent second revision", 
 
799
        >>> commit(clone, "Committing divergent second revision", 
710
800
        ...               verbose=False)
711
801
        >>> sb.common_ancestor(clone)[0]
712
802
        1
745
835
        return len(self.revision_history())
746
836
 
747
837
 
748
 
    def last_patch(self):
 
838
    def last_revision(self):
749
839
        """Return last patch hash, or None if no history.
750
840
        """
751
841
        ph = self.revision_history()
755
845
            return None
756
846
 
757
847
 
758
 
    def missing_revisions(self, other, stop_revision=None):
759
 
        """
 
848
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
 
849
        """Return a list of new revisions that would perfectly fit.
 
850
        
760
851
        If self and other have not diverged, return a list of the revisions
761
852
        present in other, but missing from self.
762
853
 
782
873
        Traceback (most recent call last):
783
874
        DivergedBranches: These branches have diverged.
784
875
        """
 
876
        # FIXME: If the branches have diverged, but the latest
 
877
        # revision in this branch is completely merged into the other,
 
878
        # then we should still be able to pull.
785
879
        self_history = self.revision_history()
786
880
        self_len = len(self_history)
787
881
        other_history = other.revision_history()
793
887
 
794
888
        if stop_revision is None:
795
889
            stop_revision = other_len
796
 
        elif stop_revision > other_len:
797
 
            raise NoSuchRevision(self, stop_revision)
798
 
        
 
890
        else:
 
891
            assert isinstance(stop_revision, int)
 
892
            if stop_revision > other_len:
 
893
                raise bzrlib.errors.NoSuchRevision(self, stop_revision)
799
894
        return other_history[self_len:stop_revision]
800
895
 
801
 
 
802
896
    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
 
        
 
897
        """Pull in new perfect-fit revisions."""
 
898
        from bzrlib.fetch import greedy_fetch
 
899
        from bzrlib.revision import get_intervening_revisions
 
900
        if stop_revision is None:
 
901
            stop_revision = other.last_revision()
 
902
        greedy_fetch(to_branch=self, from_branch=other,
 
903
                     revision=stop_revision)
 
904
        pullable_revs = self.missing_revisions(
 
905
            other, other.revision_id_to_revno(stop_revision))
 
906
        if pullable_revs:
 
907
            greedy_fetch(to_branch=self,
 
908
                         from_branch=other,
 
909
                         revision=pullable_revs[-1])
 
910
            self.append_revision(*pullable_revs)
 
911
    
 
912
 
870
913
    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
 
914
        from bzrlib.commit import Commit
 
915
        Commit().commit(self, *args, **kw)
 
916
    
 
917
    def revision_id_to_revno(self, revision_id):
 
918
        """Given a revision id, return its revno"""
 
919
        if revision_id is None:
 
920
            return 0
 
921
        history = self.revision_history()
 
922
        try:
 
923
            return history.index(revision_id) + 1
 
924
        except ValueError:
 
925
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
926
 
 
927
    def get_rev_id(self, revno, history=None):
 
928
        """Find the revision id of the specified revno."""
 
929
        if revno == 0:
 
930
            return None
 
931
        if history is None:
 
932
            history = self.revision_history()
 
933
        elif revno <= 0 or revno > len(history):
 
934
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
935
        return history[revno - 1]
1032
936
 
1033
937
    def revision_tree(self, revision_id):
1034
938
        """Return Tree for a revision on this branch.
1041
945
            return EmptyTree()
1042
946
        else:
1043
947
            inv = self.get_revision_inventory(revision_id)
1044
 
            return RevisionTree(self.text_store, inv)
 
948
            return RevisionTree(self.weave_store, inv, revision_id)
1045
949
 
1046
950
 
1047
951
    def working_tree(self):
1048
952
        """Return a `Tree` for the working copy."""
1049
 
        from workingtree import WorkingTree
 
953
        from bzrlib.workingtree import WorkingTree
1050
954
        return WorkingTree(self.base, self.read_working_inventory())
1051
955
 
1052
956
 
1055
959
 
1056
960
        If there are no revisions yet, return an `EmptyTree`.
1057
961
        """
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
 
 
 
962
        return self.revision_tree(self.last_revision())
1064
963
 
1065
964
 
1066
965
    def rename_one(self, from_rel, to_rel):
1098
997
 
1099
998
            inv.rename(file_id, to_dir_id, to_tail)
1100
999
 
1101
 
            print "%s => %s" % (from_rel, to_rel)
1102
 
 
1103
1000
            from_abs = self.abspath(from_rel)
1104
1001
            to_abs = self.abspath(to_rel)
1105
1002
            try:
1106
 
                os.rename(from_abs, to_abs)
 
1003
                rename(from_abs, to_abs)
1107
1004
            except OSError, e:
1108
1005
                raise BzrError("failed to rename %r to %r: %s"
1109
1006
                        % (from_abs, to_abs, e[1]),
1124
1021
 
1125
1022
        Note that to_name is only the last component of the new name;
1126
1023
        this doesn't change the directory.
 
1024
 
 
1025
        This returns a list of (from_path, to_path) pairs for each
 
1026
        entry that is moved.
1127
1027
        """
 
1028
        result = []
1128
1029
        self.lock_write()
1129
1030
        try:
1130
1031
            ## TODO: Option to move IDs only
1165
1066
            for f in from_paths:
1166
1067
                name_tail = splitpath(f)[-1]
1167
1068
                dest_path = appendpath(to_name, name_tail)
1168
 
                print "%s => %s" % (f, dest_path)
 
1069
                result.append((f, dest_path))
1169
1070
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1170
1071
                try:
1171
 
                    os.rename(self.abspath(f), self.abspath(dest_path))
 
1072
                    rename(self.abspath(f), self.abspath(dest_path))
1172
1073
                except OSError, e:
1173
1074
                    raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1174
1075
                            ["rename rolled back"])
1177
1078
        finally:
1178
1079
            self.unlock()
1179
1080
 
 
1081
        return result
 
1082
 
1180
1083
 
1181
1084
    def revert(self, filenames, old_tree=None, backups=True):
1182
1085
        """Restore selected files to the versions from a previous tree.
1238
1141
 
1239
1142
 
1240
1143
    def add_pending_merge(self, revision_id):
1241
 
        from bzrlib.revision import validate_revision_id
1242
 
 
1243
1144
        validate_revision_id(revision_id)
1244
 
 
 
1145
        # TODO: Perhaps should check at this point that the
 
1146
        # history of the revision is actually present?
1245
1147
        p = self.pending_merges()
1246
1148
        if revision_id in p:
1247
1149
            return
1264
1166
            self.unlock()
1265
1167
 
1266
1168
 
1267
 
 
1268
 
class ScratchBranch(Branch):
 
1169
    def get_parent(self):
 
1170
        """Return the parent location of the branch.
 
1171
 
 
1172
        This is the default location for push/pull/missing.  The usual
 
1173
        pattern is that the user can override it by specifying a
 
1174
        location.
 
1175
        """
 
1176
        import errno
 
1177
        _locs = ['parent', 'pull', 'x-pull']
 
1178
        for l in _locs:
 
1179
            try:
 
1180
                return self.controlfile(l, 'r').read().strip('\n')
 
1181
            except IOError, e:
 
1182
                if e.errno != errno.ENOENT:
 
1183
                    raise
 
1184
        return None
 
1185
 
 
1186
 
 
1187
    def set_parent(self, url):
 
1188
        # TODO: Maybe delete old location files?
 
1189
        from bzrlib.atomicfile import AtomicFile
 
1190
        self.lock_write()
 
1191
        try:
 
1192
            f = AtomicFile(self.controlfilename('parent'))
 
1193
            try:
 
1194
                f.write(url + '\n')
 
1195
                f.commit()
 
1196
            finally:
 
1197
                f.close()
 
1198
        finally:
 
1199
            self.unlock()
 
1200
 
 
1201
    def check_revno(self, revno):
 
1202
        """\
 
1203
        Check whether a revno corresponds to any revision.
 
1204
        Zero (the NULL revision) is considered valid.
 
1205
        """
 
1206
        if revno != 0:
 
1207
            self.check_real_revno(revno)
 
1208
            
 
1209
    def check_real_revno(self, revno):
 
1210
        """\
 
1211
        Check whether a revno corresponds to a real revision.
 
1212
        Zero (the NULL revision) is considered invalid
 
1213
        """
 
1214
        if revno < 1 or revno > self.revno():
 
1215
            raise InvalidRevisionNumber(revno)
 
1216
        
 
1217
        
 
1218
        
 
1219
 
 
1220
 
 
1221
class ScratchBranch(LocalBranch):
1269
1222
    """Special test class: a branch that cleans up after itself.
1270
1223
 
1271
1224
    >>> b = ScratchBranch()
1288
1241
        if base is None:
1289
1242
            base = mkdtemp()
1290
1243
            init = True
1291
 
        Branch.__init__(self, base, init=init)
 
1244
        LocalBranch.__init__(self, base, init=init)
1292
1245
        for d in dirs:
1293
1246
            os.mkdir(self.abspath(d))
1294
1247
            
1300
1253
        """
1301
1254
        >>> orig = ScratchBranch(files=["file1", "file2"])
1302
1255
        >>> clone = orig.clone()
1303
 
        >>> os.path.samefile(orig.base, clone.base)
 
1256
        >>> if os.name != 'nt':
 
1257
        ...   os.path.samefile(orig.base, clone.base)
 
1258
        ... else:
 
1259
        ...   orig.base == clone.base
 
1260
        ...
1304
1261
        False
1305
1262
        >>> os.path.isfile(os.path.join(clone.base, "file1"))
1306
1263
        True
1311
1268
        os.rmdir(base)
1312
1269
        copytree(self.base, base, symlinks=True)
1313
1270
        return ScratchBranch(base=base)
 
1271
 
 
1272
 
1314
1273
        
1315
1274
    def __del__(self):
1316
1275
        self.destroy()
1386
1345
    """Return a new tree-root file id."""
1387
1346
    return gen_file_id('TREE_ROOT')
1388
1347
 
 
1348