~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Robert Collins
  • Date: 2005-11-22 21:28:30 UTC
  • mfrom: (1185.33.32 bzr.dev)
  • Revision ID: robertc@robertcollins.net-20051122212830-885c284847f0b17b
Merge from mpool.

Show diffs side-by-side

added added

removed removed

Lines of Context:
51
51
from bzrlib.transport import Transport, get_transport
52
52
import bzrlib.xml5
53
53
import bzrlib.ui
 
54
from config import TreeConfig
54
55
 
55
56
 
56
57
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
110
111
        """Open a branch which may be of an old format.
111
112
        
112
113
        Only local branches are supported."""
113
 
        return _Branch(get_transport(base), relax_version_check=True)
 
114
        return BzrBranch(get_transport(base), relax_version_check=True)
114
115
        
115
116
    @staticmethod
116
117
    def open(base):
117
118
        """Open an existing branch, rooted at 'base' (url)"""
118
119
        t = get_transport(base)
119
120
        mutter("trying to open %r with transport %r", base, t)
120
 
        return _Branch(t)
 
121
        return BzrBranch(t)
121
122
 
122
123
    @staticmethod
123
124
    def open_containing(url):
132
133
        t = get_transport(url)
133
134
        while True:
134
135
            try:
135
 
                return _Branch(t), t.relpath(url)
 
136
                return BzrBranch(t), t.relpath(url)
136
137
            except NotBranchError:
137
138
                pass
138
139
            new_t = t.clone('..')
145
146
    def initialize(base):
146
147
        """Create a new branch, rooted at 'base' (url)"""
147
148
        t = get_transport(base)
148
 
        return _Branch(t, init=True)
 
149
        return BzrBranch(t, init=True)
149
150
 
150
151
    def setup_caching(self, cache_root):
151
152
        """Subclasses that care about caching should override this, and set
153
154
        """
154
155
        self.cache_root = cache_root
155
156
 
156
 
 
157
 
class _Branch(Branch):
 
157
    def _get_nick(self):
 
158
        cfg = self.tree_config()
 
159
        return cfg.get_option(u"nickname", default=self.base.split('/')[-1])
 
160
 
 
161
    def _set_nick(self, nick):
 
162
        cfg = self.tree_config()
 
163
        cfg.set_option(nick, "nickname")
 
164
        assert cfg.get_option("nickname") == nick
 
165
 
 
166
    nick = property(_get_nick, _set_nick)
 
167
        
 
168
    def push_stores(self, branch_to):
 
169
        """Copy the content of this branches store to branch_to."""
 
170
        raise NotImplementedError('push_stores is abstract')
 
171
 
 
172
    def get_transaction(self):
 
173
        """Return the current active transaction.
 
174
 
 
175
        If no transaction is active, this returns a passthrough object
 
176
        for which all data is immediately flushed and no caching happens.
 
177
        """
 
178
        raise NotImplementedError('get_transaction is abstract')
 
179
 
 
180
    def lock_write(self):
 
181
        raise NotImplementedError('lock_write is abstract')
 
182
        
 
183
    def lock_read(self):
 
184
        raise NotImplementedError('lock_read is abstract')
 
185
 
 
186
    def unlock(self):
 
187
        raise NotImplementedError('unlock is abstract')
 
188
 
 
189
    def abspath(self, name):
 
190
        """Return absolute filename for something in the branch
 
191
        
 
192
        XXX: Robert Collins 20051017 what is this used for? why is it a branch
 
193
        method and not a tree method.
 
194
        """
 
195
        raise NotImplementedError('abspath is abstract')
 
196
 
 
197
    def controlfilename(self, file_or_path):
 
198
        """Return location relative to branch."""
 
199
        raise NotImplementedError('controlfilename is abstract')
 
200
 
 
201
    def controlfile(self, file_or_path, mode='r'):
 
202
        """Open a control file for this branch.
 
203
 
 
204
        There are two classes of file in the control directory: text
 
205
        and binary.  binary files are untranslated byte streams.  Text
 
206
        control files are stored with Unix newlines and in UTF-8, even
 
207
        if the platform or locale defaults are different.
 
208
 
 
209
        Controlfiles should almost never be opened in write mode but
 
210
        rather should be atomically copied and replaced using atomicfile.
 
211
        """
 
212
        raise NotImplementedError('controlfile is abstract')
 
213
 
 
214
    def put_controlfile(self, path, f, encode=True):
 
215
        """Write an entry as a controlfile.
 
216
 
 
217
        :param path: The path to put the file, relative to the .bzr control
 
218
                     directory
 
219
        :param f: A file-like or string object whose contents should be copied.
 
220
        :param encode:  If true, encode the contents as utf-8
 
221
        """
 
222
        raise NotImplementedError('put_controlfile is abstract')
 
223
 
 
224
    def put_controlfiles(self, files, encode=True):
 
225
        """Write several entries as controlfiles.
 
226
 
 
227
        :param files: A list of [(path, file)] pairs, where the path is the directory
 
228
                      underneath the bzr control directory
 
229
        :param encode:  If true, encode the contents as utf-8
 
230
        """
 
231
        raise NotImplementedError('put_controlfiles is abstract')
 
232
 
 
233
    def get_root_id(self):
 
234
        """Return the id of this branches root"""
 
235
        raise NotImplementedError('get_root_id is abstract')
 
236
 
 
237
    def set_root_id(self, file_id):
 
238
        raise NotImplementedError('set_root_id is abstract')
 
239
 
 
240
    def add(self, files, ids=None):
 
241
        """Make files versioned.
 
242
 
 
243
        Note that the command line normally calls smart_add instead,
 
244
        which can automatically recurse.
 
245
 
 
246
        This puts the files in the Added state, so that they will be
 
247
        recorded by the next commit.
 
248
 
 
249
        files
 
250
            List of paths to add, relative to the base of the tree.
 
251
 
 
252
        ids
 
253
            If set, use these instead of automatically generated ids.
 
254
            Must be the same length as the list of files, but may
 
255
            contain None for ids that are to be autogenerated.
 
256
 
 
257
        TODO: Perhaps have an option to add the ids even if the files do
 
258
              not (yet) exist.
 
259
 
 
260
        TODO: Perhaps yield the ids and paths as they're added.
 
261
        """
 
262
        raise NotImplementedError('add is abstract')
 
263
 
 
264
    def print_file(self, file, revno):
 
265
        """Print `file` to stdout."""
 
266
        raise NotImplementedError('print_file is abstract')
 
267
 
 
268
    def unknowns(self):
 
269
        """Return all unknown files.
 
270
 
 
271
        These are files in the working directory that are not versioned or
 
272
        control files or ignored.
 
273
        
 
274
        >>> from bzrlib.workingtree import WorkingTree
 
275
        >>> b = ScratchBranch(files=['foo', 'foo~'])
 
276
        >>> map(str, b.unknowns())
 
277
        ['foo']
 
278
        >>> b.add('foo')
 
279
        >>> list(b.unknowns())
 
280
        []
 
281
        >>> WorkingTree(b.base, b).remove('foo')
 
282
        >>> list(b.unknowns())
 
283
        [u'foo']
 
284
        """
 
285
        raise NotImplementedError('unknowns is abstract')
 
286
 
 
287
    def append_revision(self, *revision_ids):
 
288
        raise NotImplementedError('append_revision is abstract')
 
289
 
 
290
    def set_revision_history(self, rev_history):
 
291
        raise NotImplementedError('set_revision_history is abstract')
 
292
 
 
293
    def has_revision(self, revision_id):
 
294
        """True if this branch has a copy of the revision.
 
295
 
 
296
        This does not necessarily imply the revision is merge
 
297
        or on the mainline."""
 
298
        raise NotImplementedError('has_revision is abstract')
 
299
 
 
300
    def get_revision_xml_file(self, revision_id):
 
301
        """Return XML file object for revision object."""
 
302
        raise NotImplementedError('get_revision_xml_file is abstract')
 
303
 
 
304
    def get_revision_xml(self, revision_id):
 
305
        raise NotImplementedError('get_revision_xml is abstract')
 
306
 
 
307
    def get_revision(self, revision_id):
 
308
        """Return the Revision object for a named revision"""
 
309
        raise NotImplementedError('get_revision is abstract')
 
310
 
 
311
    def get_revision_delta(self, revno):
 
312
        """Return the delta for one revision.
 
313
 
 
314
        The delta is relative to its mainline predecessor, or the
 
315
        empty tree for revision 1.
 
316
        """
 
317
        assert isinstance(revno, int)
 
318
        rh = self.revision_history()
 
319
        if not (1 <= revno <= len(rh)):
 
320
            raise InvalidRevisionNumber(revno)
 
321
 
 
322
        # revno is 1-based; list is 0-based
 
323
 
 
324
        new_tree = self.revision_tree(rh[revno-1])
 
325
        if revno == 1:
 
326
            old_tree = EmptyTree()
 
327
        else:
 
328
            old_tree = self.revision_tree(rh[revno-2])
 
329
 
 
330
        return compare_trees(old_tree, new_tree)
 
331
 
 
332
    def get_revision_sha1(self, revision_id):
 
333
        """Hash the stored value of a revision, and return it."""
 
334
        raise NotImplementedError('get_revision_sha1 is abstract')
 
335
 
 
336
    def get_ancestry(self, revision_id):
 
337
        """Return a list of revision-ids integrated by a revision.
 
338
        
 
339
        This currently returns a list, but the ordering is not guaranteed:
 
340
        treat it as a set.
 
341
        """
 
342
        raise NotImplementedError('get_ancestry is abstract')
 
343
 
 
344
    def get_inventory(self, revision_id):
 
345
        """Get Inventory object by hash."""
 
346
        raise NotImplementedError('get_inventory is abstract')
 
347
 
 
348
    def get_inventory_xml(self, revision_id):
 
349
        """Get inventory XML as a file object."""
 
350
        raise NotImplementedError('get_inventory_xml is abstract')
 
351
 
 
352
    def get_inventory_sha1(self, revision_id):
 
353
        """Return the sha1 hash of the inventory entry."""
 
354
        raise NotImplementedError('get_inventory_sha1 is abstract')
 
355
 
 
356
    def get_revision_inventory(self, revision_id):
 
357
        """Return inventory of a past revision."""
 
358
        raise NotImplementedError('get_revision_inventory is abstract')
 
359
 
 
360
    def revision_history(self):
 
361
        """Return sequence of revision hashes on to this branch."""
 
362
        raise NotImplementedError('revision_history is abstract')
 
363
 
 
364
    def revno(self):
 
365
        """Return current revision number for this branch.
 
366
 
 
367
        That is equivalent to the number of revisions committed to
 
368
        this branch.
 
369
        """
 
370
        return len(self.revision_history())
 
371
 
 
372
    def last_revision(self):
 
373
        """Return last patch hash, or None if no history."""
 
374
        ph = self.revision_history()
 
375
        if ph:
 
376
            return ph[-1]
 
377
        else:
 
378
            return None
 
379
 
 
380
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
 
381
        """Return a list of new revisions that would perfectly fit.
 
382
        
 
383
        If self and other have not diverged, return a list of the revisions
 
384
        present in other, but missing from self.
 
385
 
 
386
        >>> from bzrlib.commit import commit
 
387
        >>> bzrlib.trace.silent = True
 
388
        >>> br1 = ScratchBranch()
 
389
        >>> br2 = ScratchBranch()
 
390
        >>> br1.missing_revisions(br2)
 
391
        []
 
392
        >>> commit(br2, "lala!", rev_id="REVISION-ID-1")
 
393
        >>> br1.missing_revisions(br2)
 
394
        [u'REVISION-ID-1']
 
395
        >>> br2.missing_revisions(br1)
 
396
        []
 
397
        >>> commit(br1, "lala!", rev_id="REVISION-ID-1")
 
398
        >>> br1.missing_revisions(br2)
 
399
        []
 
400
        >>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
 
401
        >>> br1.missing_revisions(br2)
 
402
        [u'REVISION-ID-2A']
 
403
        >>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
 
404
        >>> br1.missing_revisions(br2)
 
405
        Traceback (most recent call last):
 
406
        DivergedBranches: These branches have diverged.
 
407
        """
 
408
        self_history = self.revision_history()
 
409
        self_len = len(self_history)
 
410
        other_history = other.revision_history()
 
411
        other_len = len(other_history)
 
412
        common_index = min(self_len, other_len) -1
 
413
        if common_index >= 0 and \
 
414
            self_history[common_index] != other_history[common_index]:
 
415
            raise DivergedBranches(self, other)
 
416
 
 
417
        if stop_revision is None:
 
418
            stop_revision = other_len
 
419
        else:
 
420
            assert isinstance(stop_revision, int)
 
421
            if stop_revision > other_len:
 
422
                raise bzrlib.errors.NoSuchRevision(self, stop_revision)
 
423
        return other_history[self_len:stop_revision]
 
424
    
 
425
    def update_revisions(self, other, stop_revision=None):
 
426
        """Pull in new perfect-fit revisions."""
 
427
        raise NotImplementedError('update_revisions is abstract')
 
428
 
 
429
    def pullable_revisions(self, other, stop_revision):
 
430
        raise NotImplementedError('pullable_revisions is abstract')
 
431
        
 
432
    def revision_id_to_revno(self, revision_id):
 
433
        """Given a revision id, return its revno"""
 
434
        if revision_id is None:
 
435
            return 0
 
436
        history = self.revision_history()
 
437
        try:
 
438
            return history.index(revision_id) + 1
 
439
        except ValueError:
 
440
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
441
 
 
442
    def get_rev_id(self, revno, history=None):
 
443
        """Find the revision id of the specified revno."""
 
444
        if revno == 0:
 
445
            return None
 
446
        if history is None:
 
447
            history = self.revision_history()
 
448
        elif revno <= 0 or revno > len(history):
 
449
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
450
        return history[revno - 1]
 
451
 
 
452
    def revision_tree(self, revision_id):
 
453
        """Return Tree for a revision on this branch.
 
454
 
 
455
        `revision_id` may be None for the null revision, in which case
 
456
        an `EmptyTree` is returned."""
 
457
        raise NotImplementedError('revision_tree is abstract')
 
458
 
 
459
    def working_tree(self):
 
460
        """Return a `Tree` for the working copy."""
 
461
        raise NotImplementedError('working_tree is abstract')
 
462
 
 
463
    def pull(self, source, overwrite=False):
 
464
        raise NotImplementedError('pull is abstract')
 
465
 
 
466
    def basis_tree(self):
 
467
        """Return `Tree` object for last revision.
 
468
 
 
469
        If there are no revisions yet, return an `EmptyTree`.
 
470
        """
 
471
        return self.revision_tree(self.last_revision())
 
472
 
 
473
    def rename_one(self, from_rel, to_rel):
 
474
        """Rename one file.
 
475
 
 
476
        This can change the directory or the filename or both.
 
477
        """
 
478
        raise NotImplementedError('rename_one is abstract')
 
479
 
 
480
    def move(self, from_paths, to_name):
 
481
        """Rename files.
 
482
 
 
483
        to_name must exist as a versioned directory.
 
484
 
 
485
        If to_name exists and is a directory, the files are moved into
 
486
        it, keeping their old names.  If it is a directory, 
 
487
 
 
488
        Note that to_name is only the last component of the new name;
 
489
        this doesn't change the directory.
 
490
 
 
491
        This returns a list of (from_path, to_path) pairs for each
 
492
        entry that is moved.
 
493
        """
 
494
        raise NotImplementedError('move is abstract')
 
495
 
 
496
    def revert(self, filenames, old_tree=None, backups=True):
 
497
        """Restore selected files to the versions from a previous tree.
 
498
 
 
499
        backups
 
500
            If true (default) backups are made of files before
 
501
            they're renamed.
 
502
        """
 
503
        raise NotImplementedError('revert is abstract')
 
504
 
 
505
    def pending_merges(self):
 
506
        """Return a list of pending merges.
 
507
 
 
508
        These are revisions that have been merged into the working
 
509
        directory but not yet committed.
 
510
        """
 
511
        raise NotImplementedError('pending_merges is abstract')
 
512
 
 
513
    def add_pending_merge(self, *revision_ids):
 
514
        # TODO: Perhaps should check at this point that the
 
515
        # history of the revision is actually present?
 
516
        raise NotImplementedError('add_pending_merge is abstract')
 
517
 
 
518
    def set_pending_merges(self, rev_list):
 
519
        raise NotImplementedError('set_pending_merges is abstract')
 
520
 
 
521
    def get_parent(self):
 
522
        """Return the parent location of the branch.
 
523
 
 
524
        This is the default location for push/pull/missing.  The usual
 
525
        pattern is that the user can override it by specifying a
 
526
        location.
 
527
        """
 
528
        raise NotImplementedError('get_parent is abstract')
 
529
 
 
530
    def get_push_location(self):
 
531
        """Return the None or the location to push this branch to."""
 
532
        raise NotImplementedError('get_push_location is abstract')
 
533
 
 
534
    def set_push_location(self, location):
 
535
        """Set a new push location for this branch."""
 
536
        raise NotImplementedError('set_push_location is abstract')
 
537
 
 
538
    def set_parent(self, url):
 
539
        raise NotImplementedError('set_parent is abstract')
 
540
 
 
541
    def check_revno(self, revno):
 
542
        """\
 
543
        Check whether a revno corresponds to any revision.
 
544
        Zero (the NULL revision) is considered valid.
 
545
        """
 
546
        if revno != 0:
 
547
            self.check_real_revno(revno)
 
548
            
 
549
    def check_real_revno(self, revno):
 
550
        """\
 
551
        Check whether a revno corresponds to a real revision.
 
552
        Zero (the NULL revision) is considered invalid
 
553
        """
 
554
        if revno < 1 or revno > self.revno():
 
555
            raise InvalidRevisionNumber(revno)
 
556
        
 
557
    def sign_revision(self, revision_id, gpg_strategy):
 
558
        raise NotImplementedError('sign_revision is abstract')
 
559
 
 
560
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
 
561
        raise NotImplementedError('store_revision_signature is abstract')
 
562
 
 
563
class BzrBranch(Branch):
158
564
    """A branch stored in the actual filesystem.
159
565
 
160
566
    Note that it's "local" in the context of the filesystem; it doesn't
186
592
    REVISION_NAMESPACES = {}
187
593
 
188
594
    def push_stores(self, branch_to):
189
 
        """Copy the content of this branches store to branch_to."""
 
595
        """See Branch.push_stores."""
190
596
        if (self._branch_format != branch_to._branch_format
191
597
            or self._branch_format != 4):
192
598
            from bzrlib.fetch import greedy_fetch
309
715
        transaction.finish()
310
716
 
311
717
    def get_transaction(self):
312
 
        """Return the current active transaction.
313
 
 
314
 
        If no transaction is active, this returns a passthrough object
315
 
        for which all data is immediately flushed and no caching happens.
316
 
        """
 
718
        """See Branch.get_transaction."""
317
719
        if self._transaction is None:
318
720
            return transactions.PassThroughTransaction()
319
721
        else:
371
773
            self._lock_mode = self._lock_count = None
372
774
 
373
775
    def abspath(self, name):
374
 
        """Return absolute filename for something in the branch
375
 
        
376
 
        XXX: Robert Collins 20051017 what is this used for? why is it a branch
377
 
        method and not a tree method.
378
 
        """
 
776
        """See Branch.abspath."""
379
777
        return self._transport.abspath(name)
380
778
 
381
779
    def _rel_controlfilename(self, file_or_path):
386
784
        return bzrlib.transport.urlescape(bzrlib.BZRDIR + '/' + file_or_path)
387
785
 
388
786
    def controlfilename(self, file_or_path):
389
 
        """Return location relative to branch."""
 
787
        """See Branch.controlfilename."""
390
788
        return self._transport.abspath(self._rel_controlfilename(file_or_path))
391
789
 
392
790
    def controlfile(self, file_or_path, mode='r'):
393
 
        """Open a control file for this branch.
394
 
 
395
 
        There are two classes of file in the control directory: text
396
 
        and binary.  binary files are untranslated byte streams.  Text
397
 
        control files are stored with Unix newlines and in UTF-8, even
398
 
        if the platform or locale defaults are different.
399
 
 
400
 
        Controlfiles should almost never be opened in write mode but
401
 
        rather should be atomically copied and replaced using atomicfile.
402
 
        """
 
791
        """See Branch.controlfile."""
403
792
        import codecs
404
793
 
405
794
        relpath = self._rel_controlfilename(file_or_path)
421
810
            raise BzrError("invalid controlfile mode %r" % mode)
422
811
 
423
812
    def put_controlfile(self, path, f, encode=True):
424
 
        """Write an entry as a controlfile.
425
 
 
426
 
        :param path: The path to put the file, relative to the .bzr control
427
 
                     directory
428
 
        :param f: A file-like or string object whose contents should be copied.
429
 
        :param encode:  If true, encode the contents as utf-8
430
 
        """
 
813
        """See Branch.put_controlfile."""
431
814
        self.put_controlfiles([(path, f)], encode=encode)
432
815
 
433
816
    def put_controlfiles(self, files, encode=True):
434
 
        """Write several entries as controlfiles.
435
 
 
436
 
        :param files: A list of [(path, file)] pairs, where the path is the directory
437
 
                      underneath the bzr control directory
438
 
        :param encode:  If true, encode the contents as utf-8
439
 
        """
 
817
        """See Branch.put_controlfiles."""
440
818
        import codecs
441
819
        ctrl_files = []
442
820
        for path, f in files:
513
891
                            ' and "bzr init" again'])
514
892
 
515
893
    def get_root_id(self):
516
 
        """Return the id of this branches root"""
 
894
        """See Branch.get_root_id."""
517
895
        inv = self.get_inventory(self.last_revision())
518
896
        return inv.root.file_id
519
897
 
520
898
    @needs_write_lock
 
899
    def set_root_id(self, file_id):
 
900
        """See Branch.set_root_id."""
 
901
        inv = self.working_tree().read_working_inventory()
 
902
        orig_root_id = inv.root.file_id
 
903
        del inv._byid[inv.root.file_id]
 
904
        inv.root.file_id = file_id
 
905
        inv._byid[inv.root.file_id] = inv.root
 
906
        for fid in inv:
 
907
            entry = inv[fid]
 
908
            if entry.parent_id in (None, orig_root_id):
 
909
                entry.parent_id = inv.root.file_id
 
910
        self._write_inventory(inv)
 
911
 
 
912
    @needs_write_lock
521
913
    def add(self, files, ids=None):
522
 
        """Make files versioned.
523
 
 
524
 
        Note that the command line normally calls smart_add instead,
525
 
        which can automatically recurse.
526
 
 
527
 
        This puts the files in the Added state, so that they will be
528
 
        recorded by the next commit.
529
 
 
530
 
        files
531
 
            List of paths to add, relative to the base of the tree.
532
 
 
533
 
        ids
534
 
            If set, use these instead of automatically generated ids.
535
 
            Must be the same length as the list of files, but may
536
 
            contain None for ids that are to be autogenerated.
537
 
 
538
 
        TODO: Perhaps have an option to add the ids even if the files do
539
 
              not (yet) exist.
540
 
 
541
 
        TODO: Perhaps yield the ids and paths as they're added.
542
 
        """
 
914
        """See Branch.add."""
543
915
        # TODO: Re-adding a file that is removed in the working copy
544
916
        # should probably put it back with the previous ID.
545
917
        if isinstance(files, basestring):
585
957
 
586
958
    @needs_read_lock
587
959
    def print_file(self, file, revno):
588
 
        """Print `file` to stdout."""
 
960
        """See Branch.print_file."""
589
961
        tree = self.revision_tree(self.get_rev_id(revno))
590
962
        # use inventory as it was in that revision
591
963
        file_id = tree.inventory.path2id(file)
594
966
        tree.print_file(file_id)
595
967
 
596
968
    def unknowns(self):
597
 
        """Return all unknown files.
598
 
 
599
 
        These are files in the working directory that are not versioned or
600
 
        control files or ignored.
601
 
        
602
 
        >>> from bzrlib.workingtree import WorkingTree
603
 
        >>> b = ScratchBranch(files=['foo', 'foo~'])
604
 
        >>> map(str, b.unknowns())
605
 
        ['foo']
606
 
        >>> b.add('foo')
607
 
        >>> list(b.unknowns())
608
 
        []
609
 
        >>> WorkingTree(b.base, b).remove('foo')
610
 
        >>> list(b.unknowns())
611
 
        [u'foo']
612
 
        """
 
969
        """See Branch.unknowns."""
613
970
        return self.working_tree().unknowns()
614
971
 
615
972
    @needs_write_lock
616
973
    def append_revision(self, *revision_ids):
 
974
        """See Branch.append_revision."""
617
975
        for revision_id in revision_ids:
618
976
            mutter("add {%s} to revision-history" % revision_id)
619
977
        rev_history = self.revision_history()
622
980
 
623
981
    @needs_write_lock
624
982
    def set_revision_history(self, rev_history):
 
983
        """See Branch.set_revision_history."""
625
984
        self.put_controlfile('revision-history', '\n'.join(rev_history))
626
985
 
627
986
    def has_revision(self, revision_id):
628
 
        """True if this branch has a copy of the revision.
629
 
 
630
 
        This does not necessarily imply the revision is merge
631
 
        or on the mainline."""
 
987
        """See Branch.has_revision."""
632
988
        return (revision_id is None
633
989
                or self.revision_store.has_id(revision_id))
634
990
 
635
991
    @needs_read_lock
636
992
    def get_revision_xml_file(self, revision_id):
637
 
        """Return XML file object for revision object."""
 
993
        """See Branch.get_revision_xml_file."""
638
994
        if not revision_id or not isinstance(revision_id, basestring):
639
995
            raise InvalidRevisionId(revision_id=revision_id, branch=self)
640
996
        try:
646
1002
    get_revision_xml = get_revision_xml_file
647
1003
 
648
1004
    def get_revision_xml(self, revision_id):
 
1005
        """See Branch.get_revision_xml."""
649
1006
        return self.get_revision_xml_file(revision_id).read()
650
1007
 
651
1008
 
652
1009
    def get_revision(self, revision_id):
653
 
        """Return the Revision object for a named revision"""
 
1010
        """See Branch.get_revision."""
654
1011
        xml_file = self.get_revision_xml_file(revision_id)
655
1012
 
656
1013
        try:
663
1020
        assert r.revision_id == revision_id
664
1021
        return r
665
1022
 
666
 
    def get_revision_delta(self, revno):
667
 
        """Return the delta for one revision.
668
 
 
669
 
        The delta is relative to its mainline predecessor, or the
670
 
        empty tree for revision 1.
671
 
        """
672
 
        assert isinstance(revno, int)
673
 
        rh = self.revision_history()
674
 
        if not (1 <= revno <= len(rh)):
675
 
            raise InvalidRevisionNumber(revno)
676
 
 
677
 
        # revno is 1-based; list is 0-based
678
 
 
679
 
        new_tree = self.revision_tree(rh[revno-1])
680
 
        if revno == 1:
681
 
            old_tree = EmptyTree()
682
 
        else:
683
 
            old_tree = self.revision_tree(rh[revno-2])
684
 
 
685
 
        return compare_trees(old_tree, new_tree)
686
 
 
687
1023
    def get_revision_sha1(self, revision_id):
688
 
        """Hash the stored value of a revision, and return it."""
 
1024
        """See Branch.get_revision_sha1."""
689
1025
        # In the future, revision entries will be signed. At that
690
1026
        # point, it is probably best *not* to include the signature
691
1027
        # in the revision hash. Because that lets you re-sign
695
1031
        return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
696
1032
 
697
1033
    def get_ancestry(self, revision_id):
698
 
        """Return a list of revision-ids integrated by a revision.
699
 
        
700
 
        This currently returns a list, but the ordering is not guaranteed:
701
 
        treat it as a set.
702
 
        """
 
1034
        """See Branch.get_ancestry."""
703
1035
        if revision_id is None:
704
1036
            return [None]
705
 
        w = self.get_inventory_weave()
 
1037
        w = self._get_inventory_weave()
706
1038
        return [None] + map(w.idx_to_name,
707
1039
                            w.inclusions([w.lookup(revision_id)]))
708
1040
 
709
 
    def get_inventory_weave(self):
 
1041
    def _get_inventory_weave(self):
710
1042
        return self.control_weaves.get_weave('inventory',
711
1043
                                             self.get_transaction())
712
1044
 
713
1045
    def get_inventory(self, revision_id):
714
 
        """Get Inventory object by hash."""
 
1046
        """See Branch.get_inventory."""
715
1047
        xml = self.get_inventory_xml(revision_id)
716
1048
        return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
717
1049
 
718
1050
    def get_inventory_xml(self, revision_id):
719
 
        """Get inventory XML as a file object."""
 
1051
        """See Branch.get_inventory_xml."""
720
1052
        try:
721
1053
            assert isinstance(revision_id, basestring), type(revision_id)
722
 
            iw = self.get_inventory_weave()
 
1054
            iw = self._get_inventory_weave()
723
1055
            return iw.get_text(iw.lookup(revision_id))
724
1056
        except IndexError:
725
1057
            raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
726
1058
 
727
1059
    def get_inventory_sha1(self, revision_id):
728
 
        """Return the sha1 hash of the inventory entry
729
 
        """
 
1060
        """See Branch.get_inventory_sha1."""
730
1061
        return self.get_revision(revision_id).inventory_sha1
731
1062
 
732
1063
    def get_revision_inventory(self, revision_id):
733
 
        """Return inventory of a past revision."""
 
1064
        """See Branch.get_revision_inventory."""
734
1065
        # TODO: Unify this with get_inventory()
735
1066
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
736
1067
        # must be the same as its revision, so this is trivial.
746
1077
 
747
1078
    @needs_read_lock
748
1079
    def revision_history(self):
749
 
        """Return sequence of revision hashes on to this branch."""
 
1080
        """See Branch.revision_history."""
750
1081
        transaction = self.get_transaction()
751
1082
        history = transaction.map.find_revision_history()
752
1083
        if history is not None:
760
1091
        # transaction.register_clean(history, precious=True)
761
1092
        return list(history)
762
1093
 
763
 
    def revno(self):
764
 
        """Return current revision number for this branch.
765
 
 
766
 
        That is equivalent to the number of revisions committed to
767
 
        this branch.
768
 
        """
769
 
        return len(self.revision_history())
770
 
 
771
 
    def last_revision(self):
772
 
        """Return last patch hash, or None if no history.
773
 
        """
774
 
        ph = self.revision_history()
775
 
        if ph:
776
 
            return ph[-1]
777
 
        else:
778
 
            return None
779
 
 
780
 
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
781
 
        """Return a list of new revisions that would perfectly fit.
782
 
        
783
 
        If self and other have not diverged, return a list of the revisions
784
 
        present in other, but missing from self.
785
 
 
786
 
        >>> from bzrlib.commit import commit
787
 
        >>> bzrlib.trace.silent = True
788
 
        >>> br1 = ScratchBranch()
789
 
        >>> br2 = ScratchBranch()
790
 
        >>> br1.missing_revisions(br2)
791
 
        []
792
 
        >>> commit(br2, "lala!", rev_id="REVISION-ID-1")
793
 
        >>> br1.missing_revisions(br2)
794
 
        [u'REVISION-ID-1']
795
 
        >>> br2.missing_revisions(br1)
796
 
        []
797
 
        >>> commit(br1, "lala!", rev_id="REVISION-ID-1")
798
 
        >>> br1.missing_revisions(br2)
799
 
        []
800
 
        >>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
801
 
        >>> br1.missing_revisions(br2)
802
 
        [u'REVISION-ID-2A']
803
 
        >>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
804
 
        >>> br1.missing_revisions(br2)
805
 
        Traceback (most recent call last):
806
 
        DivergedBranches: These branches have diverged.
807
 
        """
808
 
        self_history = self.revision_history()
809
 
        self_len = len(self_history)
810
 
        other_history = other.revision_history()
811
 
        other_len = len(other_history)
812
 
        common_index = min(self_len, other_len) -1
813
 
        if common_index >= 0 and \
814
 
            self_history[common_index] != other_history[common_index]:
815
 
            raise DivergedBranches(self, other)
816
 
 
817
 
        if stop_revision is None:
818
 
            stop_revision = other_len
819
 
        else:
820
 
            assert isinstance(stop_revision, int)
821
 
            if stop_revision > other_len:
822
 
                raise bzrlib.errors.NoSuchRevision(self, stop_revision)
823
 
        return other_history[self_len:stop_revision]
824
 
 
825
1094
    def update_revisions(self, other, stop_revision=None):
826
 
        """Pull in new perfect-fit revisions."""
 
1095
        """See Branch.update_revisions."""
827
1096
        from bzrlib.fetch import greedy_fetch
828
1097
        if stop_revision is None:
829
1098
            stop_revision = other.last_revision()
838
1107
            self.append_revision(*pullable_revs)
839
1108
 
840
1109
    def pullable_revisions(self, other, stop_revision):
 
1110
        """See Branch.pullable_revisions."""
841
1111
        other_revno = other.revision_id_to_revno(stop_revision)
842
1112
        try:
843
1113
            return self.missing_revisions(other, other_revno)
874
1144
        return history[revno - 1]
875
1145
 
876
1146
    def revision_tree(self, revision_id):
877
 
        """Return Tree for a revision on this branch.
878
 
 
879
 
        `revision_id` may be None for the null revision, in which case
880
 
        an `EmptyTree` is returned."""
 
1147
        """See Branch.revision_tree."""
881
1148
        # TODO: refactor this to use an existing revision object
882
1149
        # so we don't need to read it in twice.
883
1150
        if revision_id == None or revision_id == NULL_REVISION:
887
1154
            return RevisionTree(self.weave_store, inv, revision_id)
888
1155
 
889
1156
    def working_tree(self):
890
 
        """Return a `Tree` for the working copy."""
 
1157
        """See Branch.working_tree."""
891
1158
        from bzrlib.workingtree import WorkingTree
892
1159
        # TODO: In the future, perhaps WorkingTree should utilize Transport
893
1160
        # RobertCollins 20051003 - I don't think it should - working trees are
900
1167
 
901
1168
    @needs_write_lock
902
1169
    def pull(self, source, overwrite=False):
 
1170
        """See Branch.pull."""
903
1171
        source.lock_read()
904
1172
        try:
905
1173
            try:
911
1179
        finally:
912
1180
            source.unlock()
913
1181
 
914
 
    def basis_tree(self):
915
 
        """Return `Tree` object for last revision.
916
 
 
917
 
        If there are no revisions yet, return an `EmptyTree`.
918
 
        """
919
 
        return self.revision_tree(self.last_revision())
920
 
 
921
1182
    @needs_write_lock
922
1183
    def rename_one(self, from_rel, to_rel):
923
 
        """Rename one file.
924
 
 
925
 
        This can change the directory or the filename or both.
926
 
        """
 
1184
        """See Branch.rename_one."""
927
1185
        tree = self.working_tree()
928
1186
        inv = tree.inventory
929
1187
        if not tree.has_filename(from_rel):
965
1223
 
966
1224
    @needs_write_lock
967
1225
    def move(self, from_paths, to_name):
968
 
        """Rename files.
969
 
 
970
 
        to_name must exist as a versioned directory.
971
 
 
972
 
        If to_name exists and is a directory, the files are moved into
973
 
        it, keeping their old names.  If it is a directory, 
974
 
 
975
 
        Note that to_name is only the last component of the new name;
976
 
        this doesn't change the directory.
977
 
 
978
 
        This returns a list of (from_path, to_path) pairs for each
979
 
        entry that is moved.
980
 
        """
 
1226
        """See Branch.move."""
981
1227
        result = []
982
1228
        ## TODO: Option to move IDs only
983
1229
        assert not isinstance(from_paths, basestring)
1029
1275
        return result
1030
1276
 
1031
1277
    def get_parent(self):
1032
 
        """Return the parent location of the branch.
1033
 
 
1034
 
        This is the default location for push/pull/missing.  The usual
1035
 
        pattern is that the user can override it by specifying a
1036
 
        location.
1037
 
        """
 
1278
        """See Branch.get_parent."""
1038
1279
        import errno
1039
1280
        _locs = ['parent', 'pull', 'x-pull']
1040
1281
        for l in _locs:
1046
1287
        return None
1047
1288
 
1048
1289
    def get_push_location(self):
1049
 
        """Return the None or the location to push this branch to."""
 
1290
        """See Branch.get_push_location."""
1050
1291
        config = bzrlib.config.BranchConfig(self)
1051
1292
        push_loc = config.get_user_option('push_location')
1052
1293
        return push_loc
1053
1294
 
1054
1295
    def set_push_location(self, location):
1055
 
        """Set a new push location for this branch."""
 
1296
        """See Branch.set_push_location."""
1056
1297
        config = bzrlib.config.LocationConfig(self.base)
1057
1298
        config.set_user_option('push_location', location)
1058
1299
 
1059
1300
    @needs_write_lock
1060
1301
    def set_parent(self, url):
 
1302
        """See Branch.set_parent."""
1061
1303
        # TODO: Maybe delete old location files?
1062
1304
        from bzrlib.atomicfile import AtomicFile
1063
1305
        f = AtomicFile(self.controlfilename('parent'))
1067
1309
        finally:
1068
1310
            f.close()
1069
1311
 
 
1312
    def tree_config(self):
 
1313
        return TreeConfig(self)
 
1314
 
1070
1315
    def check_revno(self, revno):
1071
1316
        """\
1072
1317
        Check whether a revno corresponds to any revision.
1084
1329
            raise InvalidRevisionNumber(revno)
1085
1330
        
1086
1331
    def sign_revision(self, revision_id, gpg_strategy):
 
1332
        """See Branch.sign_revision."""
1087
1333
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
1088
1334
        self.store_revision_signature(gpg_strategy, plaintext, revision_id)
1089
1335
 
1090
1336
    @needs_write_lock
1091
1337
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
 
1338
        """See Branch.store_revision_signature."""
1092
1339
        self.revision_store.add(StringIO(gpg_strategy.sign(plaintext)), 
1093
1340
                                revision_id, "sig")
1094
1341
 
1095
1342
 
1096
 
class ScratchBranch(_Branch):
 
1343
class ScratchBranch(BzrBranch):
1097
1344
    """Special test class: a branch that cleans up after itself.
1098
1345
 
1099
1346
    >>> b = ScratchBranch()