1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
from cStringIO import StringIO
19
from bzrlib.lazy_import import lazy_import
20
lazy_import(globals(), """
38
revision as _mod_revision,
43
from bzrlib.bundle import serializer
44
from bzrlib.revisiontree import RevisionTree
45
from bzrlib.store.versioned import VersionedFileStore
46
from bzrlib.store.text import TextStore
47
from bzrlib.testament import Testament
51
from bzrlib.decorators import needs_read_lock, needs_write_lock
52
from bzrlib.inter import InterObject
53
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
54
from bzrlib.symbol_versioning import (
58
from bzrlib.trace import mutter, note, warning
61
# Old formats display a warning, but only once
62
_deprecation_warning_done = False
65
######################################################################
68
class Repository(object):
69
"""Repository holding history for one or more branches.
71
The repository holds and retrieves historical information including
72
revisions and file history. It's normally accessed only by the Branch,
73
which views a particular line of development through that history.
75
The Repository builds on top of Stores and a Transport, which respectively
76
describe the disk data format and the way of accessing the (possibly
80
_file_ids_altered_regex = lazy_regex.lazy_compile(
81
r'file_id="(?P<file_id>[^"]+)"'
82
r'.*revision="(?P<revision_id>[^"]+)"'
85
def abort_write_group(self):
86
"""Commit the contents accrued within the current write group.
88
:seealso: start_write_group.
90
if self._write_group is not self.get_transaction():
91
# has an unlock or relock occured ?
92
raise errors.BzrError('mismatched lock context and write group.')
93
self._abort_write_group()
94
self._write_group = None
96
def _abort_write_group(self):
97
"""Template method for per-repository write group cleanup.
99
This is called during abort before the write group is considered to be
100
finished and should cleanup any internal state accrued during the write
101
group. There is no requirement that data handed to the repository be
102
*not* made available - this is not a rollback - but neither should any
103
attempt be made to ensure that data added is fully commited. Abort is
104
invoked when an error has occured so futher disk or network operations
105
may not be possible or may error and if possible should not be
110
def add_inventory(self, revision_id, inv, parents):
111
"""Add the inventory inv to the repository as revision_id.
113
:param parents: The revision ids of the parents that revision_id
114
is known to have and are in the repository already.
116
returns the sha1 of the serialized inventory.
118
revision_id = osutils.safe_revision_id(revision_id)
119
_mod_revision.check_not_reserved_id(revision_id)
120
assert inv.revision_id is None or inv.revision_id == revision_id, \
121
"Mismatch between inventory revision" \
122
" id and insertion revid (%r, %r)" % (inv.revision_id, revision_id)
123
assert inv.root is not None
124
inv_text = self.serialise_inventory(inv)
125
inv_sha1 = osutils.sha_string(inv_text)
126
inv_vf = self.control_weaves.get_weave('inventory',
127
self.get_transaction())
128
self._inventory_add_lines(inv_vf, revision_id, parents,
129
osutils.split_lines(inv_text))
132
def _inventory_add_lines(self, inv_vf, revision_id, parents, lines):
134
for parent in parents:
136
final_parents.append(parent)
138
inv_vf.add_lines(revision_id, final_parents, lines)
141
def add_revision(self, revision_id, rev, inv=None, config=None):
142
"""Add rev to the revision store as revision_id.
144
:param revision_id: the revision id to use.
145
:param rev: The revision object.
146
:param inv: The inventory for the revision. if None, it will be looked
147
up in the inventory storer
148
:param config: If None no digital signature will be created.
149
If supplied its signature_needed method will be used
150
to determine if a signature should be made.
152
revision_id = osutils.safe_revision_id(revision_id)
153
# TODO: jam 20070210 Shouldn't we check rev.revision_id and
155
_mod_revision.check_not_reserved_id(revision_id)
156
if config is not None and config.signature_needed():
158
inv = self.get_inventory(revision_id)
159
plaintext = Testament(rev, inv).as_short_text()
160
self.store_revision_signature(
161
gpg.GPGStrategy(config), plaintext, revision_id)
162
if not revision_id in self.get_inventory_weave():
164
raise errors.WeaveRevisionNotPresent(revision_id,
165
self.get_inventory_weave())
167
# yes, this is not suitable for adding with ghosts.
168
self.add_inventory(revision_id, inv, rev.parent_ids)
169
self._revision_store.add_revision(rev, self.get_transaction())
171
def _add_revision_text(self, revision_id, text):
172
revision = self._revision_store._serializer.read_revision_from_string(
174
self._revision_store._add_revision(revision, StringIO(text),
175
self.get_transaction())
178
def _all_possible_ids(self):
179
"""Return all the possible revisions that we could find."""
180
return self.get_inventory_weave().versions()
182
def all_revision_ids(self):
183
"""Returns a list of all the revision ids in the repository.
185
This is deprecated because code should generally work on the graph
186
reachable from a particular revision, and ignore any other revisions
187
that might be present. There is no direct replacement method.
189
return self._all_revision_ids()
192
def _all_revision_ids(self):
193
"""Returns a list of all the revision ids in the repository.
195
These are in as much topological order as the underlying store can
196
present: for weaves ghosts may lead to a lack of correctness until
197
the reweave updates the parents list.
199
if self._revision_store.text_store.listable():
200
return self._revision_store.all_revision_ids(self.get_transaction())
201
result = self._all_possible_ids()
202
# TODO: jam 20070210 Ensure that _all_possible_ids returns non-unicode
203
# ids. (It should, since _revision_store's API should change to
204
# return utf8 revision_ids)
205
return self._eliminate_revisions_not_present(result)
207
def break_lock(self):
208
"""Break a lock if one is present from another instance.
210
Uses the ui factory to ask for confirmation if the lock may be from
213
self.control_files.break_lock()
216
def _eliminate_revisions_not_present(self, revision_ids):
217
"""Check every revision id in revision_ids to see if we have it.
219
Returns a set of the present revisions.
222
for id in revision_ids:
223
if self.has_revision(id):
228
def create(a_bzrdir):
229
"""Construct the current default format repository in a_bzrdir."""
230
return RepositoryFormat.get_default_format().initialize(a_bzrdir)
232
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
233
"""instantiate a Repository.
235
:param _format: The format of the repository on disk.
236
:param a_bzrdir: The BzrDir of the repository.
238
In the future we will have a single api for all stores for
239
getting file texts, inventories and revisions, then
240
this construct will accept instances of those things.
242
super(Repository, self).__init__()
243
self._format = _format
244
# the following are part of the public API for Repository:
245
self.bzrdir = a_bzrdir
246
self.control_files = control_files
247
self._revision_store = _revision_store
248
self.text_store = text_store
249
# backwards compatibility
250
self.weave_store = text_store
251
# not right yet - should be more semantically clear ?
253
self.control_store = control_store
254
self.control_weaves = control_store
255
# TODO: make sure to construct the right store classes, etc, depending
256
# on whether escaping is required.
257
self._warn_if_deprecated()
258
self._write_group = None
261
return '%s(%r)' % (self.__class__.__name__,
262
self.bzrdir.transport.base)
264
def is_in_write_group(self):
265
"""Return True if there is an open write group.
267
:seealso: start_write_group.
269
return self._write_group is not None
272
return self.control_files.is_locked()
274
def lock_write(self, token=None):
275
"""Lock this repository for writing.
277
:param token: if this is already locked, then lock_write will fail
278
unless the token matches the existing lock.
279
:returns: a token if this instance supports tokens, otherwise None.
280
:raises TokenLockingNotSupported: when a token is given but this
281
instance doesn't support using token locks.
282
:raises MismatchedToken: if the specified token doesn't match the token
283
of the existing lock.
285
A token should be passed in if you know that you have locked the object
286
some other way, and need to synchronise this object's state with that
289
XXX: this docstring is duplicated in many places, e.g. lockable_files.py
291
result = self.control_files.lock_write(token=token)
296
self.control_files.lock_read()
299
def get_physical_lock_status(self):
300
return self.control_files.get_physical_lock_status()
302
def leave_lock_in_place(self):
303
"""Tell this repository not to release the physical lock when this
306
If lock_write doesn't return a token, then this method is not supported.
308
self.control_files.leave_in_place()
310
def dont_leave_lock_in_place(self):
311
"""Tell this repository to release the physical lock when this
312
object is unlocked, even if it didn't originally acquire it.
314
If lock_write doesn't return a token, then this method is not supported.
316
self.control_files.dont_leave_in_place()
319
def gather_stats(self, revid=None, committers=None):
320
"""Gather statistics from a revision id.
322
:param revid: The revision id to gather statistics from, if None, then
323
no revision specific statistics are gathered.
324
:param committers: Optional parameter controlling whether to grab
325
a count of committers from the revision specific statistics.
326
:return: A dictionary of statistics. Currently this contains:
327
committers: The number of committers if requested.
328
firstrev: A tuple with timestamp, timezone for the penultimate left
329
most ancestor of revid, if revid is not the NULL_REVISION.
330
latestrev: A tuple with timestamp, timezone for revid, if revid is
331
not the NULL_REVISION.
332
revisions: The total revision count in the repository.
333
size: An estimate disk size of the repository in bytes.
336
if revid and committers:
337
result['committers'] = 0
338
if revid and revid != _mod_revision.NULL_REVISION:
340
all_committers = set()
341
revisions = self.get_ancestry(revid)
342
# pop the leading None
344
first_revision = None
346
# ignore the revisions in the middle - just grab first and last
347
revisions = revisions[0], revisions[-1]
348
for revision in self.get_revisions(revisions):
349
if not first_revision:
350
first_revision = revision
352
all_committers.add(revision.committer)
353
last_revision = revision
355
result['committers'] = len(all_committers)
356
result['firstrev'] = (first_revision.timestamp,
357
first_revision.timezone)
358
result['latestrev'] = (last_revision.timestamp,
359
last_revision.timezone)
361
# now gather global repository information
362
if self.bzrdir.root_transport.listable():
363
c, t = self._revision_store.total_size(self.get_transaction())
364
result['revisions'] = c
369
def missing_revision_ids(self, other, revision_id=None):
370
"""Return the revision ids that other has that this does not.
372
These are returned in topological order.
374
revision_id: only return revision ids included by revision_id.
376
revision_id = osutils.safe_revision_id(revision_id)
377
return InterRepository.get(other, self).missing_revision_ids(revision_id)
381
"""Open the repository rooted at base.
383
For instance, if the repository is at URL/.bzr/repository,
384
Repository.open(URL) -> a Repository instance.
386
control = bzrdir.BzrDir.open(base)
387
return control.open_repository()
389
def copy_content_into(self, destination, revision_id=None):
390
"""Make a complete copy of the content in self into destination.
392
This is a destructive operation! Do not use it on existing
395
revision_id = osutils.safe_revision_id(revision_id)
396
return InterRepository.get(self, destination).copy_content(revision_id)
398
def commit_write_group(self):
399
"""Commit the contents accrued within the current write group.
401
:seealso: start_write_group.
403
if self._write_group is not self.get_transaction():
404
# has an unlock or relock occured ?
405
raise errors.BzrError('mismatched lock context and write group.')
406
self._commit_write_group()
407
self._write_group = None
409
def _commit_write_group(self):
410
"""Template method for per-repository write group cleanup.
412
This is called before the write group is considered to be
413
finished and should ensure that all data handed to the repository
414
for writing during the write group is safely committed (to the
415
extent possible considering file system caching etc).
418
def fetch(self, source, revision_id=None, pb=None):
419
"""Fetch the content required to construct revision_id from source.
421
If revision_id is None all content is copied.
423
revision_id = osutils.safe_revision_id(revision_id)
424
inter = InterRepository.get(source, self)
426
return inter.fetch(revision_id=revision_id, pb=pb)
427
except NotImplementedError:
428
raise errors.IncompatibleRepositories(source, self)
430
def create_bundle(self, target, base, fileobj, format=None):
431
return serializer.write_bundle(self, target, base, fileobj, format)
433
def get_commit_builder(self, branch, parents, config, timestamp=None,
434
timezone=None, committer=None, revprops=None,
436
"""Obtain a CommitBuilder for this repository.
438
:param branch: Branch to commit to.
439
:param parents: Revision ids of the parents of the new revision.
440
:param config: Configuration to use.
441
:param timestamp: Optional timestamp recorded for commit.
442
:param timezone: Optional timezone for timestamp.
443
:param committer: Optional committer to set for commit.
444
:param revprops: Optional dictionary of revision properties.
445
:param revision_id: Optional revision id.
447
revision_id = osutils.safe_revision_id(revision_id)
448
result =_CommitBuilder(self, parents, config, timestamp, timezone,
449
committer, revprops, revision_id)
450
self.start_write_group()
454
if (self.control_files._lock_count == 1 and
455
self.control_files._lock_mode == 'w'):
456
if self._write_group is not None:
457
raise errors.BzrError(
458
'Must end write groups before releasing write locks.')
459
self.control_files.unlock()
462
def clone(self, a_bzrdir, revision_id=None):
463
"""Clone this repository into a_bzrdir using the current format.
465
Currently no check is made that the format of this repository and
466
the bzrdir format are compatible. FIXME RBC 20060201.
468
:return: The newly created destination repository.
470
# TODO: deprecate after 0.16; cloning this with all its settings is
471
# probably not very useful -- mbp 20070423
472
dest_repo = self._create_sprouting_repo(a_bzrdir, shared=self.is_shared())
473
self.copy_content_into(dest_repo, revision_id)
476
def start_write_group(self):
477
"""Start a write group in the repository.
479
Write groups are used by repositories which do not have a 1:1 mapping
480
between file ids and backend store to manage the insertion of data from
481
both fetch and commit operations.
483
A write lock is required around the start_write_group/commit_write_group
484
for the support of lock-requiring repository formats.
486
if not self.is_locked() or self.control_files._lock_mode != 'w':
487
raise errors.NotWriteLocked(self)
488
if self._write_group:
489
raise errors.BzrError('already in a write group')
490
self._start_write_group()
491
# so we can detect unlock/relock - the write group is now entered.
492
self._write_group = self.get_transaction()
494
def _start_write_group(self):
495
"""Template method for per-repository write group startup.
497
This is called before the write group is considered to be
502
def sprout(self, to_bzrdir, revision_id=None):
503
"""Create a descendent repository for new development.
505
Unlike clone, this does not copy the settings of the repository.
507
dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
508
dest_repo.fetch(self, revision_id=revision_id)
511
def _create_sprouting_repo(self, a_bzrdir, shared):
512
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
513
# use target default format.
514
dest_repo = a_bzrdir.create_repository()
516
# Most control formats need the repository to be specifically
517
# created, but on some old all-in-one formats it's not needed
519
dest_repo = self._format.initialize(a_bzrdir, shared=shared)
520
except errors.UninitializableFormat:
521
dest_repo = a_bzrdir.open_repository()
525
def has_revision(self, revision_id):
526
"""True if this repository has a copy of the revision."""
527
revision_id = osutils.safe_revision_id(revision_id)
528
return self._revision_store.has_revision_id(revision_id,
529
self.get_transaction())
532
def get_revision_reconcile(self, revision_id):
533
"""'reconcile' helper routine that allows access to a revision always.
535
This variant of get_revision does not cross check the weave graph
536
against the revision one as get_revision does: but it should only
537
be used by reconcile, or reconcile-alike commands that are correcting
538
or testing the revision graph.
540
if not revision_id or not isinstance(revision_id, basestring):
541
raise errors.InvalidRevisionId(revision_id=revision_id,
543
return self.get_revisions([revision_id])[0]
546
def get_revisions(self, revision_ids):
547
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
548
revs = self._revision_store.get_revisions(revision_ids,
549
self.get_transaction())
551
assert not isinstance(rev.revision_id, unicode)
552
for parent_id in rev.parent_ids:
553
assert not isinstance(parent_id, unicode)
557
def get_revision_xml(self, revision_id):
558
# TODO: jam 20070210 This shouldn't be necessary since get_revision
559
# would have already do it.
560
# TODO: jam 20070210 Just use _serializer.write_revision_to_string()
561
revision_id = osutils.safe_revision_id(revision_id)
562
rev = self.get_revision(revision_id)
564
# the current serializer..
565
self._revision_store._serializer.write_revision(rev, rev_tmp)
567
return rev_tmp.getvalue()
570
def get_revision(self, revision_id):
571
"""Return the Revision object for a named revision"""
572
# TODO: jam 20070210 get_revision_reconcile should do this for us
573
revision_id = osutils.safe_revision_id(revision_id)
574
r = self.get_revision_reconcile(revision_id)
575
# weave corruption can lead to absent revision markers that should be
577
# the following test is reasonably cheap (it needs a single weave read)
578
# and the weave is cached in read transactions. In write transactions
579
# it is not cached but typically we only read a small number of
580
# revisions. For knits when they are introduced we will probably want
581
# to ensure that caching write transactions are in use.
582
inv = self.get_inventory_weave()
583
self._check_revision_parents(r, inv)
587
def get_deltas_for_revisions(self, revisions):
588
"""Produce a generator of revision deltas.
590
Note that the input is a sequence of REVISIONS, not revision_ids.
591
Trees will be held in memory until the generator exits.
592
Each delta is relative to the revision's lefthand predecessor.
594
required_trees = set()
595
for revision in revisions:
596
required_trees.add(revision.revision_id)
597
required_trees.update(revision.parent_ids[:1])
598
trees = dict((t.get_revision_id(), t) for
599
t in self.revision_trees(required_trees))
600
for revision in revisions:
601
if not revision.parent_ids:
602
old_tree = self.revision_tree(None)
604
old_tree = trees[revision.parent_ids[0]]
605
yield trees[revision.revision_id].changes_from(old_tree)
608
def get_revision_delta(self, revision_id):
609
"""Return the delta for one revision.
611
The delta is relative to the left-hand predecessor of the
614
r = self.get_revision(revision_id)
615
return list(self.get_deltas_for_revisions([r]))[0]
617
def _check_revision_parents(self, revision, inventory):
618
"""Private to Repository and Fetch.
620
This checks the parentage of revision in an inventory weave for
621
consistency and is only applicable to inventory-weave-for-ancestry
622
using repository formats & fetchers.
624
weave_parents = inventory.get_parents(revision.revision_id)
625
weave_names = inventory.versions()
626
for parent_id in revision.parent_ids:
627
if parent_id in weave_names:
628
# this parent must not be a ghost.
629
if not parent_id in weave_parents:
631
raise errors.CorruptRepository(self)
634
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
635
revision_id = osutils.safe_revision_id(revision_id)
636
signature = gpg_strategy.sign(plaintext)
637
self._revision_store.add_revision_signature_text(revision_id,
639
self.get_transaction())
641
def fileids_altered_by_revision_ids(self, revision_ids):
642
"""Find the file ids and versions affected by revisions.
644
:param revisions: an iterable containing revision ids.
645
:return: a dictionary mapping altered file-ids to an iterable of
646
revision_ids. Each altered file-ids has the exact revision_ids that
647
altered it listed explicitly.
649
assert self._serializer.support_altered_by_hack, \
650
("fileids_altered_by_revision_ids only supported for branches "
651
"which store inventory as unnested xml, not on %r" % self)
652
selected_revision_ids = set(osutils.safe_revision_id(r)
653
for r in revision_ids)
654
w = self.get_inventory_weave()
657
# this code needs to read every new line in every inventory for the
658
# inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
659
# not present in one of those inventories is unnecessary but not
660
# harmful because we are filtering by the revision id marker in the
661
# inventory lines : we only select file ids altered in one of those
662
# revisions. We don't need to see all lines in the inventory because
663
# only those added in an inventory in rev X can contain a revision=X
665
unescape_revid_cache = {}
666
unescape_fileid_cache = {}
668
# jam 20061218 In a big fetch, this handles hundreds of thousands
669
# of lines, so it has had a lot of inlining and optimizing done.
670
# Sorry that it is a little bit messy.
671
# Move several functions to be local variables, since this is a long
673
search = self._file_ids_altered_regex.search
674
unescape = _unescape_xml
675
setdefault = result.setdefault
676
pb = ui.ui_factory.nested_progress_bar()
678
for line in w.iter_lines_added_or_present_in_versions(
679
selected_revision_ids, pb=pb):
683
# One call to match.group() returning multiple items is quite a
684
# bit faster than 2 calls to match.group() each returning 1
685
file_id, revision_id = match.group('file_id', 'revision_id')
687
# Inlining the cache lookups helps a lot when you make 170,000
688
# lines and 350k ids, versus 8.4 unique ids.
689
# Using a cache helps in 2 ways:
690
# 1) Avoids unnecessary decoding calls
691
# 2) Re-uses cached strings, which helps in future set and
693
# (2) is enough that removing encoding entirely along with
694
# the cache (so we are using plain strings) results in no
695
# performance improvement.
697
revision_id = unescape_revid_cache[revision_id]
699
unescaped = unescape(revision_id)
700
unescape_revid_cache[revision_id] = unescaped
701
revision_id = unescaped
703
if revision_id in selected_revision_ids:
705
file_id = unescape_fileid_cache[file_id]
707
unescaped = unescape(file_id)
708
unescape_fileid_cache[file_id] = unescaped
710
setdefault(file_id, set()).add(revision_id)
716
def get_inventory_weave(self):
717
return self.control_weaves.get_weave('inventory',
718
self.get_transaction())
721
def get_inventory(self, revision_id):
722
"""Get Inventory object by hash."""
723
# TODO: jam 20070210 Technically we don't need to sanitize, since all
724
# called functions must sanitize.
725
revision_id = osutils.safe_revision_id(revision_id)
726
return self.deserialise_inventory(
727
revision_id, self.get_inventory_xml(revision_id))
729
def deserialise_inventory(self, revision_id, xml):
730
"""Transform the xml into an inventory object.
732
:param revision_id: The expected revision id of the inventory.
733
:param xml: A serialised inventory.
735
revision_id = osutils.safe_revision_id(revision_id)
736
result = self._serializer.read_inventory_from_string(xml)
737
result.root.revision = revision_id
740
def serialise_inventory(self, inv):
741
return self._serializer.write_inventory_to_string(inv)
743
def get_serializer_format(self):
744
return self._serializer.format_num
747
def get_inventory_xml(self, revision_id):
748
"""Get inventory XML as a file object."""
749
revision_id = osutils.safe_revision_id(revision_id)
751
assert isinstance(revision_id, str), type(revision_id)
752
iw = self.get_inventory_weave()
753
return iw.get_text(revision_id)
755
raise errors.HistoryMissing(self, 'inventory', revision_id)
758
def get_inventory_sha1(self, revision_id):
759
"""Return the sha1 hash of the inventory entry
761
# TODO: jam 20070210 Shouldn't this be deprecated / removed?
762
revision_id = osutils.safe_revision_id(revision_id)
763
return self.get_revision(revision_id).inventory_sha1
766
def get_revision_graph(self, revision_id=None):
767
"""Return a dictionary containing the revision graph.
769
:param revision_id: The revision_id to get a graph from. If None, then
770
the entire revision graph is returned. This is a deprecated mode of
771
operation and will be removed in the future.
772
:return: a dictionary of revision_id->revision_parents_list.
774
# special case NULL_REVISION
775
if revision_id == _mod_revision.NULL_REVISION:
777
revision_id = osutils.safe_revision_id(revision_id)
778
a_weave = self.get_inventory_weave()
779
all_revisions = self._eliminate_revisions_not_present(
781
entire_graph = dict([(node, a_weave.get_parents(node)) for
782
node in all_revisions])
783
if revision_id is None:
785
elif revision_id not in entire_graph:
786
raise errors.NoSuchRevision(self, revision_id)
788
# add what can be reached from revision_id
790
pending = set([revision_id])
791
while len(pending) > 0:
793
result[node] = entire_graph[node]
794
for revision_id in result[node]:
795
if revision_id not in result:
796
pending.add(revision_id)
800
def get_revision_graph_with_ghosts(self, revision_ids=None):
801
"""Return a graph of the revisions with ghosts marked as applicable.
803
:param revision_ids: an iterable of revisions to graph or None for all.
804
:return: a Graph object with the graph reachable from revision_ids.
806
result = deprecated_graph.Graph()
808
pending = set(self.all_revision_ids())
811
pending = set(osutils.safe_revision_id(r) for r in revision_ids)
812
# special case NULL_REVISION
813
if _mod_revision.NULL_REVISION in pending:
814
pending.remove(_mod_revision.NULL_REVISION)
815
required = set(pending)
818
revision_id = pending.pop()
820
rev = self.get_revision(revision_id)
821
except errors.NoSuchRevision:
822
if revision_id in required:
825
result.add_ghost(revision_id)
827
for parent_id in rev.parent_ids:
828
# is this queued or done ?
829
if (parent_id not in pending and
830
parent_id not in done):
832
pending.add(parent_id)
833
result.add_node(revision_id, rev.parent_ids)
834
done.add(revision_id)
837
def _get_history_vf(self):
838
"""Get a versionedfile whose history graph reflects all revisions.
840
For weave repositories, this is the inventory weave.
842
return self.get_inventory_weave()
844
def iter_reverse_revision_history(self, revision_id):
845
"""Iterate backwards through revision ids in the lefthand history
847
:param revision_id: The revision id to start with. All its lefthand
848
ancestors will be traversed.
850
revision_id = osutils.safe_revision_id(revision_id)
851
if revision_id in (None, _mod_revision.NULL_REVISION):
853
next_id = revision_id
854
versionedfile = self._get_history_vf()
857
parents = versionedfile.get_parents(next_id)
858
if len(parents) == 0:
864
def get_revision_inventory(self, revision_id):
865
"""Return inventory of a past revision."""
866
# TODO: Unify this with get_inventory()
867
# bzr 0.0.6 and later imposes the constraint that the inventory_id
868
# must be the same as its revision, so this is trivial.
869
if revision_id is None:
870
# This does not make sense: if there is no revision,
871
# then it is the current tree inventory surely ?!
872
# and thus get_root_id() is something that looks at the last
873
# commit on the branch, and the get_root_id is an inventory check.
874
raise NotImplementedError
875
# return Inventory(self.get_root_id())
877
return self.get_inventory(revision_id)
881
"""Return True if this repository is flagged as a shared repository."""
882
raise NotImplementedError(self.is_shared)
885
def reconcile(self, other=None, thorough=False):
886
"""Reconcile this repository."""
887
from bzrlib.reconcile import RepoReconciler
888
reconciler = RepoReconciler(self, thorough=thorough)
889
reconciler.reconcile()
892
def _refresh_data(self):
893
"""Helper called from lock_* to ensure coherency with disk.
895
The default implementation does nothing; it is however possible
896
for repositories to maintain loaded indices across multiple locks
897
by checking inside their implementation of this method to see
898
whether their indices are still valid. This depends of course on
899
the disk format being validatable in this manner.
903
def revision_tree(self, revision_id):
904
"""Return Tree for a revision on this branch.
906
`revision_id` may be None for the empty tree revision.
908
# TODO: refactor this to use an existing revision object
909
# so we don't need to read it in twice.
910
if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
911
return RevisionTree(self, Inventory(root_id=None),
912
_mod_revision.NULL_REVISION)
914
revision_id = osutils.safe_revision_id(revision_id)
915
inv = self.get_revision_inventory(revision_id)
916
return RevisionTree(self, inv, revision_id)
919
def revision_trees(self, revision_ids):
920
"""Return Tree for a revision on this branch.
922
`revision_id` may not be None or 'null:'"""
923
assert None not in revision_ids
924
assert _mod_revision.NULL_REVISION not in revision_ids
925
texts = self.get_inventory_weave().get_texts(revision_ids)
926
for text, revision_id in zip(texts, revision_ids):
927
inv = self.deserialise_inventory(revision_id, text)
928
yield RevisionTree(self, inv, revision_id)
931
def get_ancestry(self, revision_id, topo_sorted=True):
932
"""Return a list of revision-ids integrated by a revision.
934
The first element of the list is always None, indicating the origin
935
revision. This might change when we have history horizons, or
936
perhaps we should have a new API.
938
This is topologically sorted.
940
if _mod_revision.is_null(revision_id):
942
revision_id = osutils.safe_revision_id(revision_id)
943
if not self.has_revision(revision_id):
944
raise errors.NoSuchRevision(self, revision_id)
945
w = self.get_inventory_weave()
946
candidates = w.get_ancestry(revision_id, topo_sorted)
947
return [None] + candidates # self._eliminate_revisions_not_present(candidates)
950
"""Compress the data within the repository.
952
This operation only makes sense for some repository types. For other
953
types it should be a no-op that just returns.
955
This stub method does not require a lock, but subclasses should use
956
@needs_write_lock as this is a long running call its reasonable to
957
implicitly lock for the user.
961
def print_file(self, file, revision_id):
962
"""Print `file` to stdout.
964
FIXME RBC 20060125 as John Meinel points out this is a bad api
965
- it writes to stdout, it assumes that that is valid etc. Fix
966
by creating a new more flexible convenience function.
968
revision_id = osutils.safe_revision_id(revision_id)
969
tree = self.revision_tree(revision_id)
970
# use inventory as it was in that revision
971
file_id = tree.inventory.path2id(file)
973
# TODO: jam 20060427 Write a test for this code path
974
# it had a bug in it, and was raising the wrong
976
raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
977
tree.print_file(file_id)
979
def get_transaction(self):
980
return self.control_files.get_transaction()
982
def revision_parents(self, revision_id):
983
revision_id = osutils.safe_revision_id(revision_id)
984
return self.get_inventory_weave().parent_names(revision_id)
986
def get_parents(self, revision_ids):
987
"""See StackedParentsProvider.get_parents"""
989
for revision_id in revision_ids:
990
if revision_id == _mod_revision.NULL_REVISION:
994
parents = self.get_revision(revision_id).parent_ids
995
except errors.NoSuchRevision:
998
if len(parents) == 0:
999
parents = [_mod_revision.NULL_REVISION]
1000
parents_list.append(parents)
1003
def _make_parents_provider(self):
1006
def get_graph(self, other_repository=None):
1007
"""Return the graph walker for this repository format"""
1008
parents_provider = self._make_parents_provider()
1009
if (other_repository is not None and
1010
other_repository.bzrdir.transport.base !=
1011
self.bzrdir.transport.base):
1012
parents_provider = graph._StackedParentsProvider(
1013
[parents_provider, other_repository._make_parents_provider()])
1014
return graph.Graph(parents_provider)
1017
def set_make_working_trees(self, new_value):
1018
"""Set the policy flag for making working trees when creating branches.
1020
This only applies to branches that use this repository.
1022
The default is 'True'.
1023
:param new_value: True to restore the default, False to disable making
1026
raise NotImplementedError(self.set_make_working_trees)
1028
def make_working_trees(self):
1029
"""Returns the policy for making working trees on new branches."""
1030
raise NotImplementedError(self.make_working_trees)
1033
def sign_revision(self, revision_id, gpg_strategy):
1034
revision_id = osutils.safe_revision_id(revision_id)
1035
plaintext = Testament.from_revision(self, revision_id).as_short_text()
1036
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
1039
def has_signature_for_revision_id(self, revision_id):
1040
"""Query for a revision signature for revision_id in the repository."""
1041
revision_id = osutils.safe_revision_id(revision_id)
1042
return self._revision_store.has_signature(revision_id,
1043
self.get_transaction())
1046
def get_signature_text(self, revision_id):
1047
"""Return the text for a signature."""
1048
revision_id = osutils.safe_revision_id(revision_id)
1049
return self._revision_store.get_signature_text(revision_id,
1050
self.get_transaction())
1053
def check(self, revision_ids):
1054
"""Check consistency of all history of given revision_ids.
1056
Different repository implementations should override _check().
1058
:param revision_ids: A non-empty list of revision_ids whose ancestry
1059
will be checked. Typically the last revision_id of a branch.
1061
if not revision_ids:
1062
raise ValueError("revision_ids must be non-empty in %s.check"
1064
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
1065
return self._check(revision_ids)
1067
def _check(self, revision_ids):
1068
result = check.Check(self)
1072
def _warn_if_deprecated(self):
1073
global _deprecation_warning_done
1074
if _deprecation_warning_done:
1076
_deprecation_warning_done = True
1077
warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
1078
% (self._format, self.bzrdir.transport.base))
1080
def supports_rich_root(self):
1081
return self._format.rich_root_data
1083
def _check_ascii_revisionid(self, revision_id, method):
1084
"""Private helper for ascii-only repositories."""
1085
# weave repositories refuse to store revisionids that are non-ascii.
1086
if revision_id is not None:
1087
# weaves require ascii revision ids.
1088
if isinstance(revision_id, unicode):
1090
revision_id.encode('ascii')
1091
except UnicodeEncodeError:
1092
raise errors.NonAsciiRevisionId(method, self)
1095
revision_id.decode('ascii')
1096
except UnicodeDecodeError:
1097
raise errors.NonAsciiRevisionId(method, self)
1101
# remove these delegates a while after bzr 0.15
1102
def __make_delegated(name, from_module):
1103
def _deprecated_repository_forwarder():
1104
symbol_versioning.warn('%s moved to %s in bzr 0.15'
1105
% (name, from_module),
1108
m = __import__(from_module, globals(), locals(), [name])
1110
return getattr(m, name)
1111
except AttributeError:
1112
raise AttributeError('module %s has no name %s'
1114
globals()[name] = _deprecated_repository_forwarder
1117
'AllInOneRepository',
1118
'WeaveMetaDirRepository',
1119
'PreSplitOutRepositoryFormat',
1120
'RepositoryFormat4',
1121
'RepositoryFormat5',
1122
'RepositoryFormat6',
1123
'RepositoryFormat7',
1125
__make_delegated(_name, 'bzrlib.repofmt.weaverepo')
1129
'RepositoryFormatKnit',
1130
'RepositoryFormatKnit1',
1132
__make_delegated(_name, 'bzrlib.repofmt.knitrepo')
1135
def install_revision(repository, rev, revision_tree):
1136
"""Install all revision data into a repository."""
1137
present_parents = []
1139
for p_id in rev.parent_ids:
1140
if repository.has_revision(p_id):
1141
present_parents.append(p_id)
1142
parent_trees[p_id] = repository.revision_tree(p_id)
1144
parent_trees[p_id] = repository.revision_tree(None)
1146
inv = revision_tree.inventory
1147
entries = inv.iter_entries()
1148
# backwards compatability hack: skip the root id.
1149
if not repository.supports_rich_root():
1150
path, root = entries.next()
1151
if root.revision != rev.revision_id:
1152
raise errors.IncompatibleRevision(repr(repository))
1153
# Add the texts that are not already present
1154
for path, ie in entries:
1155
w = repository.weave_store.get_weave_or_empty(ie.file_id,
1156
repository.get_transaction())
1157
if ie.revision not in w:
1159
# FIXME: TODO: The following loop *may* be overlapping/duplicate
1160
# with InventoryEntry.find_previous_heads(). if it is, then there
1161
# is a latent bug here where the parents may have ancestors of each
1163
for revision, tree in parent_trees.iteritems():
1164
if ie.file_id not in tree:
1166
parent_id = tree.inventory[ie.file_id].revision
1167
if parent_id in text_parents:
1169
text_parents.append(parent_id)
1171
vfile = repository.weave_store.get_weave_or_empty(ie.file_id,
1172
repository.get_transaction())
1173
lines = revision_tree.get_file(ie.file_id).readlines()
1174
vfile.add_lines(rev.revision_id, text_parents, lines)
1176
# install the inventory
1177
repository.add_inventory(rev.revision_id, inv, present_parents)
1178
except errors.RevisionAlreadyPresent:
1180
repository.add_revision(rev.revision_id, rev, inv)
1183
class MetaDirRepository(Repository):
1184
"""Repositories in the new meta-dir layout."""
1186
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
1187
super(MetaDirRepository, self).__init__(_format,
1193
dir_mode = self.control_files._dir_mode
1194
file_mode = self.control_files._file_mode
1197
def is_shared(self):
1198
"""Return True if this repository is flagged as a shared repository."""
1199
return self.control_files._transport.has('shared-storage')
1202
def set_make_working_trees(self, new_value):
1203
"""Set the policy flag for making working trees when creating branches.
1205
This only applies to branches that use this repository.
1207
The default is 'True'.
1208
:param new_value: True to restore the default, False to disable making
1213
self.control_files._transport.delete('no-working-trees')
1214
except errors.NoSuchFile:
1217
self.control_files.put_utf8('no-working-trees', '')
1219
def make_working_trees(self):
1220
"""Returns the policy for making working trees on new branches."""
1221
return not self.control_files._transport.has('no-working-trees')
1224
class RepositoryFormatRegistry(registry.Registry):
1225
"""Registry of RepositoryFormats.
1228
def get(self, format_string):
1229
r = registry.Registry.get(self, format_string)
1235
format_registry = RepositoryFormatRegistry()
1236
"""Registry of formats, indexed by their identifying format string.
1238
This can contain either format instances themselves, or classes/factories that
1239
can be called to obtain one.
1243
#####################################################################
1244
# Repository Formats
1246
class RepositoryFormat(object):
1247
"""A repository format.
1249
Formats provide three things:
1250
* An initialization routine to construct repository data on disk.
1251
* a format string which is used when the BzrDir supports versioned
1253
* an open routine which returns a Repository instance.
1255
Formats are placed in an dict by their format string for reference
1256
during opening. These should be subclasses of RepositoryFormat
1259
Once a format is deprecated, just deprecate the initialize and open
1260
methods on the format class. Do not deprecate the object, as the
1261
object will be created every system load.
1263
Common instance attributes:
1264
_matchingbzrdir - the bzrdir format that the repository format was
1265
originally written to work with. This can be used if manually
1266
constructing a bzrdir and repository, or more commonly for test suite
1271
return "<%s>" % self.__class__.__name__
1273
def __eq__(self, other):
1274
# format objects are generally stateless
1275
return isinstance(other, self.__class__)
1277
def __ne__(self, other):
1278
return not self == other
1281
def find_format(klass, a_bzrdir):
1282
"""Return the format for the repository object in a_bzrdir.
1284
This is used by bzr native formats that have a "format" file in
1285
the repository. Other methods may be used by different types of
1289
transport = a_bzrdir.get_repository_transport(None)
1290
format_string = transport.get("format").read()
1291
return format_registry.get(format_string)
1292
except errors.NoSuchFile:
1293
raise errors.NoRepositoryPresent(a_bzrdir)
1295
raise errors.UnknownFormatError(format=format_string)
1298
def register_format(klass, format):
1299
format_registry.register(format.get_format_string(), format)
1302
def unregister_format(klass, format):
1303
format_registry.remove(format.get_format_string())
1306
def get_default_format(klass):
1307
"""Return the current default format."""
1308
from bzrlib import bzrdir
1309
return bzrdir.format_registry.make_bzrdir('default').repository_format
1311
def _get_control_store(self, repo_transport, control_files):
1312
"""Return the control store for this repository."""
1313
raise NotImplementedError(self._get_control_store)
1315
def get_format_string(self):
1316
"""Return the ASCII format string that identifies this format.
1318
Note that in pre format ?? repositories the format string is
1319
not permitted nor written to disk.
1321
raise NotImplementedError(self.get_format_string)
1323
def get_format_description(self):
1324
"""Return the short description for this format."""
1325
raise NotImplementedError(self.get_format_description)
1327
def _get_revision_store(self, repo_transport, control_files):
1328
"""Return the revision store object for this a_bzrdir."""
1329
raise NotImplementedError(self._get_revision_store)
1331
def _get_text_rev_store(self,
1338
"""Common logic for getting a revision store for a repository.
1340
see self._get_revision_store for the subclass-overridable method to
1341
get the store for a repository.
1343
from bzrlib.store.revision.text import TextRevisionStore
1344
dir_mode = control_files._dir_mode
1345
file_mode = control_files._file_mode
1346
text_store = TextStore(transport.clone(name),
1348
compressed=compressed,
1350
file_mode=file_mode)
1351
_revision_store = TextRevisionStore(text_store, serializer)
1352
return _revision_store
1354
# TODO: this shouldn't be in the base class, it's specific to things that
1355
# use weaves or knits -- mbp 20070207
1356
def _get_versioned_file_store(self,
1361
versionedfile_class=None,
1362
versionedfile_kwargs={},
1364
if versionedfile_class is None:
1365
versionedfile_class = self._versionedfile_class
1366
weave_transport = control_files._transport.clone(name)
1367
dir_mode = control_files._dir_mode
1368
file_mode = control_files._file_mode
1369
return VersionedFileStore(weave_transport, prefixed=prefixed,
1371
file_mode=file_mode,
1372
versionedfile_class=versionedfile_class,
1373
versionedfile_kwargs=versionedfile_kwargs,
1376
def initialize(self, a_bzrdir, shared=False):
1377
"""Initialize a repository of this format in a_bzrdir.
1379
:param a_bzrdir: The bzrdir to put the new repository in it.
1380
:param shared: The repository should be initialized as a sharable one.
1381
:returns: The new repository object.
1383
This may raise UninitializableFormat if shared repository are not
1384
compatible the a_bzrdir.
1386
raise NotImplementedError(self.initialize)
1388
def is_supported(self):
1389
"""Is this format supported?
1391
Supported formats must be initializable and openable.
1392
Unsupported formats may not support initialization or committing or
1393
some other features depending on the reason for not being supported.
1397
def check_conversion_target(self, target_format):
1398
raise NotImplementedError(self.check_conversion_target)
1400
def open(self, a_bzrdir, _found=False):
1401
"""Return an instance of this format for the bzrdir a_bzrdir.
1403
_found is a private parameter, do not use it.
1405
raise NotImplementedError(self.open)
1408
class MetaDirRepositoryFormat(RepositoryFormat):
1409
"""Common base class for the new repositories using the metadir layout."""
1411
rich_root_data = False
1412
supports_tree_reference = False
1413
_matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1416
super(MetaDirRepositoryFormat, self).__init__()
1418
def _create_control_files(self, a_bzrdir):
1419
"""Create the required files and the initial control_files object."""
1420
# FIXME: RBC 20060125 don't peek under the covers
1421
# NB: no need to escape relative paths that are url safe.
1422
repository_transport = a_bzrdir.get_repository_transport(self)
1423
control_files = lockable_files.LockableFiles(repository_transport,
1424
'lock', lockdir.LockDir)
1425
control_files.create_lock()
1426
return control_files
1428
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1429
"""Upload the initial blank content."""
1430
control_files = self._create_control_files(a_bzrdir)
1431
control_files.lock_write()
1433
control_files._transport.mkdir_multi(dirs,
1434
mode=control_files._dir_mode)
1435
for file, content in files:
1436
control_files.put(file, content)
1437
for file, content in utf8_files:
1438
control_files.put_utf8(file, content)
1440
control_files.put_utf8('shared-storage', '')
1442
control_files.unlock()
1445
# formats which have no format string are not discoverable
1446
# and not independently creatable, so are not registered. They're
1447
# all in bzrlib.repofmt.weaverepo now. When an instance of one of these is
1448
# needed, it's constructed directly by the BzrDir. Non-native formats where
1449
# the repository is not separately opened are similar.
1451
format_registry.register_lazy(
1452
'Bazaar-NG Repository format 7',
1453
'bzrlib.repofmt.weaverepo',
1456
# KEEP in sync with bzrdir.format_registry default, which controls the overall
1457
# default control directory format
1459
format_registry.register_lazy(
1460
'Bazaar-NG Knit Repository Format 1',
1461
'bzrlib.repofmt.knitrepo',
1462
'RepositoryFormatKnit1',
1464
format_registry.default_key = 'Bazaar-NG Knit Repository Format 1'
1466
format_registry.register_lazy(
1467
'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
1468
'bzrlib.repofmt.knitrepo',
1469
'RepositoryFormatKnit3',
1473
class InterRepository(InterObject):
1474
"""This class represents operations taking place between two repositories.
1476
Its instances have methods like copy_content and fetch, and contain
1477
references to the source and target repositories these operations can be
1480
Often we will provide convenience methods on 'repository' which carry out
1481
operations with another repository - they will always forward to
1482
InterRepository.get(other).method_name(parameters).
1486
"""The available optimised InterRepository types."""
1488
def copy_content(self, revision_id=None):
1489
raise NotImplementedError(self.copy_content)
1491
def fetch(self, revision_id=None, pb=None):
1492
"""Fetch the content required to construct revision_id.
1494
The content is copied from self.source to self.target.
1496
:param revision_id: if None all content is copied, if NULL_REVISION no
1498
:param pb: optional progress bar to use for progress reports. If not
1499
provided a default one will be created.
1501
Returns the copied revision count and the failed revisions in a tuple:
1504
raise NotImplementedError(self.fetch)
1507
def missing_revision_ids(self, revision_id=None):
1508
"""Return the revision ids that source has that target does not.
1510
These are returned in topological order.
1512
:param revision_id: only return revision ids included by this
1515
# generic, possibly worst case, slow code path.
1516
target_ids = set(self.target.all_revision_ids())
1517
if revision_id is not None:
1518
# TODO: jam 20070210 InterRepository is internal enough that it
1519
# should assume revision_ids are already utf-8
1520
revision_id = osutils.safe_revision_id(revision_id)
1521
source_ids = self.source.get_ancestry(revision_id)
1522
assert source_ids[0] is None
1525
source_ids = self.source.all_revision_ids()
1526
result_set = set(source_ids).difference(target_ids)
1527
# this may look like a no-op: its not. It preserves the ordering
1528
# other_ids had while only returning the members from other_ids
1529
# that we've decided we need.
1530
return [rev_id for rev_id in source_ids if rev_id in result_set]
1533
class InterSameDataRepository(InterRepository):
1534
"""Code for converting between repositories that represent the same data.
1536
Data format and model must match for this to work.
1540
def _get_repo_format_to_test(self):
1541
"""Repository format for testing with."""
1542
return RepositoryFormat.get_default_format()
1545
def is_compatible(source, target):
1546
if source.supports_rich_root() != target.supports_rich_root():
1548
if source._serializer != target._serializer:
1553
def copy_content(self, revision_id=None):
1554
"""Make a complete copy of the content in self into destination.
1556
This copies both the repository's revision data, and configuration information
1557
such as the make_working_trees setting.
1559
This is a destructive operation! Do not use it on existing
1562
:param revision_id: Only copy the content needed to construct
1563
revision_id and its parents.
1566
self.target.set_make_working_trees(self.source.make_working_trees())
1567
except NotImplementedError:
1569
# TODO: jam 20070210 This is fairly internal, so we should probably
1570
# just assert that revision_id is not unicode.
1571
revision_id = osutils.safe_revision_id(revision_id)
1572
# but don't bother fetching if we have the needed data now.
1573
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1574
self.target.has_revision(revision_id)):
1576
self.target.fetch(self.source, revision_id=revision_id)
1579
def fetch(self, revision_id=None, pb=None):
1580
"""See InterRepository.fetch()."""
1581
from bzrlib.fetch import GenericRepoFetcher
1582
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1583
self.source, self.source._format, self.target,
1584
self.target._format)
1585
# TODO: jam 20070210 This should be an assert, not a translate
1586
revision_id = osutils.safe_revision_id(revision_id)
1587
f = GenericRepoFetcher(to_repository=self.target,
1588
from_repository=self.source,
1589
last_revision=revision_id,
1591
return f.count_copied, f.failed_revisions
1594
class InterWeaveRepo(InterSameDataRepository):
1595
"""Optimised code paths between Weave based repositories."""
1598
def _get_repo_format_to_test(self):
1599
from bzrlib.repofmt import weaverepo
1600
return weaverepo.RepositoryFormat7()
1603
def is_compatible(source, target):
1604
"""Be compatible with known Weave formats.
1606
We don't test for the stores being of specific types because that
1607
could lead to confusing results, and there is no need to be
1610
from bzrlib.repofmt.weaverepo import (
1616
return (isinstance(source._format, (RepositoryFormat5,
1618
RepositoryFormat7)) and
1619
isinstance(target._format, (RepositoryFormat5,
1621
RepositoryFormat7)))
1622
except AttributeError:
1626
def copy_content(self, revision_id=None):
1627
"""See InterRepository.copy_content()."""
1628
# weave specific optimised path:
1629
# TODO: jam 20070210 Internal, should be an assert, not translate
1630
revision_id = osutils.safe_revision_id(revision_id)
1632
self.target.set_make_working_trees(self.source.make_working_trees())
1633
except NotImplementedError:
1635
# FIXME do not peek!
1636
if self.source.control_files._transport.listable():
1637
pb = ui.ui_factory.nested_progress_bar()
1639
self.target.weave_store.copy_all_ids(
1640
self.source.weave_store,
1642
from_transaction=self.source.get_transaction(),
1643
to_transaction=self.target.get_transaction())
1644
pb.update('copying inventory', 0, 1)
1645
self.target.control_weaves.copy_multi(
1646
self.source.control_weaves, ['inventory'],
1647
from_transaction=self.source.get_transaction(),
1648
to_transaction=self.target.get_transaction())
1649
self.target._revision_store.text_store.copy_all_ids(
1650
self.source._revision_store.text_store,
1655
self.target.fetch(self.source, revision_id=revision_id)
1658
def fetch(self, revision_id=None, pb=None):
1659
"""See InterRepository.fetch()."""
1660
from bzrlib.fetch import GenericRepoFetcher
1661
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1662
self.source, self.source._format, self.target, self.target._format)
1663
# TODO: jam 20070210 This should be an assert, not a translate
1664
revision_id = osutils.safe_revision_id(revision_id)
1665
f = GenericRepoFetcher(to_repository=self.target,
1666
from_repository=self.source,
1667
last_revision=revision_id,
1669
return f.count_copied, f.failed_revisions
1672
def missing_revision_ids(self, revision_id=None):
1673
"""See InterRepository.missing_revision_ids()."""
1674
# we want all revisions to satisfy revision_id in source.
1675
# but we don't want to stat every file here and there.
1676
# we want then, all revisions other needs to satisfy revision_id
1677
# checked, but not those that we have locally.
1678
# so the first thing is to get a subset of the revisions to
1679
# satisfy revision_id in source, and then eliminate those that
1680
# we do already have.
1681
# this is slow on high latency connection to self, but as as this
1682
# disk format scales terribly for push anyway due to rewriting
1683
# inventory.weave, this is considered acceptable.
1685
if revision_id is not None:
1686
source_ids = self.source.get_ancestry(revision_id)
1687
assert source_ids[0] is None
1690
source_ids = self.source._all_possible_ids()
1691
source_ids_set = set(source_ids)
1692
# source_ids is the worst possible case we may need to pull.
1693
# now we want to filter source_ids against what we actually
1694
# have in target, but don't try to check for existence where we know
1695
# we do not have a revision as that would be pointless.
1696
target_ids = set(self.target._all_possible_ids())
1697
possibly_present_revisions = target_ids.intersection(source_ids_set)
1698
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1699
required_revisions = source_ids_set.difference(actually_present_revisions)
1700
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1701
if revision_id is not None:
1702
# we used get_ancestry to determine source_ids then we are assured all
1703
# revisions referenced are present as they are installed in topological order.
1704
# and the tip revision was validated by get_ancestry.
1705
return required_topo_revisions
1707
# if we just grabbed the possibly available ids, then
1708
# we only have an estimate of whats available and need to validate
1709
# that against the revision records.
1710
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1713
class InterKnitRepo(InterSameDataRepository):
1714
"""Optimised code paths between Knit based repositories."""
1717
def _get_repo_format_to_test(self):
1718
from bzrlib.repofmt import knitrepo
1719
return knitrepo.RepositoryFormatKnit1()
1722
def is_compatible(source, target):
1723
"""Be compatible with known Knit formats.
1725
We don't test for the stores being of specific types because that
1726
could lead to confusing results, and there is no need to be
1729
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1
1731
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1732
isinstance(target._format, (RepositoryFormatKnit1)))
1733
except AttributeError:
1737
def fetch(self, revision_id=None, pb=None):
1738
"""See InterRepository.fetch()."""
1739
from bzrlib.fetch import KnitRepoFetcher
1740
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1741
self.source, self.source._format, self.target, self.target._format)
1742
# TODO: jam 20070210 This should be an assert, not a translate
1743
revision_id = osutils.safe_revision_id(revision_id)
1744
f = KnitRepoFetcher(to_repository=self.target,
1745
from_repository=self.source,
1746
last_revision=revision_id,
1748
return f.count_copied, f.failed_revisions
1751
def missing_revision_ids(self, revision_id=None):
1752
"""See InterRepository.missing_revision_ids()."""
1753
if revision_id is not None:
1754
source_ids = self.source.get_ancestry(revision_id)
1755
assert source_ids[0] is None
1758
source_ids = self.source._all_possible_ids()
1759
source_ids_set = set(source_ids)
1760
# source_ids is the worst possible case we may need to pull.
1761
# now we want to filter source_ids against what we actually
1762
# have in target, but don't try to check for existence where we know
1763
# we do not have a revision as that would be pointless.
1764
target_ids = set(self.target._all_possible_ids())
1765
possibly_present_revisions = target_ids.intersection(source_ids_set)
1766
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1767
required_revisions = source_ids_set.difference(actually_present_revisions)
1768
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1769
if revision_id is not None:
1770
# we used get_ancestry to determine source_ids then we are assured all
1771
# revisions referenced are present as they are installed in topological order.
1772
# and the tip revision was validated by get_ancestry.
1773
return required_topo_revisions
1775
# if we just grabbed the possibly available ids, then
1776
# we only have an estimate of whats available and need to validate
1777
# that against the revision records.
1778
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1781
class InterModel1and2(InterRepository):
1784
def _get_repo_format_to_test(self):
1788
def is_compatible(source, target):
1789
if not source.supports_rich_root() and target.supports_rich_root():
1795
def fetch(self, revision_id=None, pb=None):
1796
"""See InterRepository.fetch()."""
1797
from bzrlib.fetch import Model1toKnit2Fetcher
1798
# TODO: jam 20070210 This should be an assert, not a translate
1799
revision_id = osutils.safe_revision_id(revision_id)
1800
f = Model1toKnit2Fetcher(to_repository=self.target,
1801
from_repository=self.source,
1802
last_revision=revision_id,
1804
return f.count_copied, f.failed_revisions
1807
def copy_content(self, revision_id=None):
1808
"""Make a complete copy of the content in self into destination.
1810
This is a destructive operation! Do not use it on existing
1813
:param revision_id: Only copy the content needed to construct
1814
revision_id and its parents.
1817
self.target.set_make_working_trees(self.source.make_working_trees())
1818
except NotImplementedError:
1820
# TODO: jam 20070210 Internal, assert, don't translate
1821
revision_id = osutils.safe_revision_id(revision_id)
1822
# but don't bother fetching if we have the needed data now.
1823
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1824
self.target.has_revision(revision_id)):
1826
self.target.fetch(self.source, revision_id=revision_id)
1829
class InterKnit1and2(InterKnitRepo):
1832
def _get_repo_format_to_test(self):
1836
def is_compatible(source, target):
1837
"""Be compatible with Knit1 source and Knit3 target"""
1838
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit3
1840
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1, \
1841
RepositoryFormatKnit3
1842
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1843
isinstance(target._format, (RepositoryFormatKnit3)))
1844
except AttributeError:
1848
def fetch(self, revision_id=None, pb=None):
1849
"""See InterRepository.fetch()."""
1850
from bzrlib.fetch import Knit1to2Fetcher
1851
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1852
self.source, self.source._format, self.target,
1853
self.target._format)
1854
# TODO: jam 20070210 This should be an assert, not a translate
1855
revision_id = osutils.safe_revision_id(revision_id)
1856
f = Knit1to2Fetcher(to_repository=self.target,
1857
from_repository=self.source,
1858
last_revision=revision_id,
1860
return f.count_copied, f.failed_revisions
1863
class InterRemoteRepository(InterRepository):
1864
"""Code for converting between RemoteRepository objects.
1866
This just gets an non-remote repository from the RemoteRepository, and calls
1867
InterRepository.get again.
1870
def __init__(self, source, target):
1871
if isinstance(source, remote.RemoteRepository):
1872
source._ensure_real()
1873
real_source = source._real_repository
1875
real_source = source
1876
if isinstance(target, remote.RemoteRepository):
1877
target._ensure_real()
1878
real_target = target._real_repository
1880
real_target = target
1881
self.real_inter = InterRepository.get(real_source, real_target)
1884
def is_compatible(source, target):
1885
if isinstance(source, remote.RemoteRepository):
1887
if isinstance(target, remote.RemoteRepository):
1891
def copy_content(self, revision_id=None):
1892
self.real_inter.copy_content(revision_id=revision_id)
1894
def fetch(self, revision_id=None, pb=None):
1895
self.real_inter.fetch(revision_id=revision_id, pb=pb)
1898
def _get_repo_format_to_test(self):
1902
InterRepository.register_optimiser(InterSameDataRepository)
1903
InterRepository.register_optimiser(InterWeaveRepo)
1904
InterRepository.register_optimiser(InterKnitRepo)
1905
InterRepository.register_optimiser(InterModel1and2)
1906
InterRepository.register_optimiser(InterKnit1and2)
1907
InterRepository.register_optimiser(InterRemoteRepository)
1910
class CopyConverter(object):
1911
"""A repository conversion tool which just performs a copy of the content.
1913
This is slow but quite reliable.
1916
def __init__(self, target_format):
1917
"""Create a CopyConverter.
1919
:param target_format: The format the resulting repository should be.
1921
self.target_format = target_format
1923
def convert(self, repo, pb):
1924
"""Perform the conversion of to_convert, giving feedback via pb.
1926
:param to_convert: The disk object to convert.
1927
:param pb: a progress bar to use for progress information.
1932
# this is only useful with metadir layouts - separated repo content.
1933
# trigger an assertion if not such
1934
repo._format.get_format_string()
1935
self.repo_dir = repo.bzrdir
1936
self.step('Moving repository to repository.backup')
1937
self.repo_dir.transport.move('repository', 'repository.backup')
1938
backup_transport = self.repo_dir.transport.clone('repository.backup')
1939
repo._format.check_conversion_target(self.target_format)
1940
self.source_repo = repo._format.open(self.repo_dir,
1942
_override_transport=backup_transport)
1943
self.step('Creating new repository')
1944
converted = self.target_format.initialize(self.repo_dir,
1945
self.source_repo.is_shared())
1946
converted.lock_write()
1948
self.step('Copying content into repository.')
1949
self.source_repo.copy_content_into(converted)
1952
self.step('Deleting old repository content.')
1953
self.repo_dir.transport.delete_tree('repository.backup')
1954
self.pb.note('repository converted')
1956
def step(self, message):
1957
"""Update the pb by a step."""
1959
self.pb.update(message, self.count, self.total)
1962
class CommitBuilder(object):
1963
"""Provides an interface to build up a commit.
1965
This allows describing a tree to be committed without needing to
1966
know the internals of the format of the repository.
1969
record_root_entry = False
1970
def __init__(self, repository, parents, config, timestamp=None,
1971
timezone=None, committer=None, revprops=None,
1973
"""Initiate a CommitBuilder.
1975
:param repository: Repository to commit to.
1976
:param parents: Revision ids of the parents of the new revision.
1977
:param config: Configuration to use.
1978
:param timestamp: Optional timestamp recorded for commit.
1979
:param timezone: Optional timezone for timestamp.
1980
:param committer: Optional committer to set for commit.
1981
:param revprops: Optional dictionary of revision properties.
1982
:param revision_id: Optional revision id.
1984
self._config = config
1986
if committer is None:
1987
self._committer = self._config.username()
1989
assert isinstance(committer, basestring), type(committer)
1990
self._committer = committer
1992
self.new_inventory = Inventory(None)
1993
self._new_revision_id = osutils.safe_revision_id(revision_id)
1994
self.parents = parents
1995
self.repository = repository
1998
if revprops is not None:
1999
self._revprops.update(revprops)
2001
if timestamp is None:
2002
timestamp = time.time()
2003
# Restrict resolution to 1ms
2004
self._timestamp = round(timestamp, 3)
2006
if timezone is None:
2007
self._timezone = osutils.local_time_offset()
2009
self._timezone = int(timezone)
2011
self._generate_revision_if_needed()
2013
def commit(self, message):
2014
"""Make the actual commit.
2016
:return: The revision id of the recorded revision.
2018
rev = _mod_revision.Revision(
2019
timestamp=self._timestamp,
2020
timezone=self._timezone,
2021
committer=self._committer,
2023
inventory_sha1=self.inv_sha1,
2024
revision_id=self._new_revision_id,
2025
properties=self._revprops)
2026
rev.parent_ids = self.parents
2027
self.repository.add_revision(self._new_revision_id, rev,
2028
self.new_inventory, self._config)
2029
self.repository.commit_write_group()
2030
return self._new_revision_id
2032
def revision_tree(self):
2033
"""Return the tree that was just committed.
2035
After calling commit() this can be called to get a RevisionTree
2036
representing the newly committed tree. This is preferred to
2037
calling Repository.revision_tree() because that may require
2038
deserializing the inventory, while we already have a copy in
2041
return RevisionTree(self.repository, self.new_inventory,
2042
self._new_revision_id)
2044
def finish_inventory(self):
2045
"""Tell the builder that the inventory is finished."""
2046
if self.new_inventory.root is None:
2047
symbol_versioning.warn('Root entry should be supplied to'
2048
' record_entry_contents, as of bzr 0.10.',
2049
DeprecationWarning, stacklevel=2)
2050
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
2051
self.new_inventory.revision_id = self._new_revision_id
2052
self.inv_sha1 = self.repository.add_inventory(
2053
self._new_revision_id,
2058
def _gen_revision_id(self):
2059
"""Return new revision-id."""
2060
return generate_ids.gen_revision_id(self._config.username(),
2063
def _generate_revision_if_needed(self):
2064
"""Create a revision id if None was supplied.
2066
If the repository can not support user-specified revision ids
2067
they should override this function and raise CannotSetRevisionId
2068
if _new_revision_id is not None.
2070
:raises: CannotSetRevisionId
2072
if self._new_revision_id is None:
2073
self._new_revision_id = self._gen_revision_id()
2075
def record_entry_contents(self, ie, parent_invs, path, tree):
2076
"""Record the content of ie from tree into the commit if needed.
2078
Side effect: sets ie.revision when unchanged
2080
:param ie: An inventory entry present in the commit.
2081
:param parent_invs: The inventories of the parent revisions of the
2083
:param path: The path the entry is at in the tree.
2084
:param tree: The tree which contains this entry and should be used to
2087
if self.new_inventory.root is None and ie.parent_id is not None:
2088
symbol_versioning.warn('Root entry should be supplied to'
2089
' record_entry_contents, as of bzr 0.10.',
2090
DeprecationWarning, stacklevel=2)
2091
self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
2093
self.new_inventory.add(ie)
2095
# ie.revision is always None if the InventoryEntry is considered
2096
# for committing. ie.snapshot will record the correct revision
2097
# which may be the sole parent if it is untouched.
2098
if ie.revision is not None:
2101
# In this revision format, root entries have no knit or weave
2102
if ie is self.new_inventory.root:
2103
# When serializing out to disk and back in
2104
# root.revision is always _new_revision_id
2105
ie.revision = self._new_revision_id
2107
previous_entries = ie.find_previous_heads(
2109
self.repository.weave_store,
2110
self.repository.get_transaction())
2111
# we are creating a new revision for ie in the history store
2113
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2115
def modified_directory(self, file_id, file_parents):
2116
"""Record the presence of a symbolic link.
2118
:param file_id: The file_id of the link to record.
2119
:param file_parents: The per-file parent revision ids.
2121
self._add_text_to_weave(file_id, [], file_parents.keys())
2123
def modified_reference(self, file_id, file_parents):
2124
"""Record the modification of a reference.
2126
:param file_id: The file_id of the link to record.
2127
:param file_parents: The per-file parent revision ids.
2129
self._add_text_to_weave(file_id, [], file_parents.keys())
2131
def modified_file_text(self, file_id, file_parents,
2132
get_content_byte_lines, text_sha1=None,
2134
"""Record the text of file file_id
2136
:param file_id: The file_id of the file to record the text of.
2137
:param file_parents: The per-file parent revision ids.
2138
:param get_content_byte_lines: A callable which will return the byte
2140
:param text_sha1: Optional SHA1 of the file contents.
2141
:param text_size: Optional size of the file contents.
2143
# mutter('storing text of file {%s} in revision {%s} into %r',
2144
# file_id, self._new_revision_id, self.repository.weave_store)
2145
# special case to avoid diffing on renames or
2147
if (len(file_parents) == 1
2148
and text_sha1 == file_parents.values()[0].text_sha1
2149
and text_size == file_parents.values()[0].text_size):
2150
previous_ie = file_parents.values()[0]
2151
versionedfile = self.repository.weave_store.get_weave(file_id,
2152
self.repository.get_transaction())
2153
versionedfile.clone_text(self._new_revision_id,
2154
previous_ie.revision, file_parents.keys())
2155
return text_sha1, text_size
2157
new_lines = get_content_byte_lines()
2158
# TODO: Rather than invoking sha_strings here, _add_text_to_weave
2159
# should return the SHA1 and size
2160
self._add_text_to_weave(file_id, new_lines, file_parents.keys())
2161
return osutils.sha_strings(new_lines), \
2162
sum(map(len, new_lines))
2164
def modified_link(self, file_id, file_parents, link_target):
2165
"""Record the presence of a symbolic link.
2167
:param file_id: The file_id of the link to record.
2168
:param file_parents: The per-file parent revision ids.
2169
:param link_target: Target location of this link.
2171
self._add_text_to_weave(file_id, [], file_parents.keys())
2173
def _add_text_to_weave(self, file_id, new_lines, parents):
2174
versionedfile = self.repository.weave_store.get_weave_or_empty(
2175
file_id, self.repository.get_transaction())
2176
versionedfile.add_lines(self._new_revision_id, parents, new_lines)
2177
versionedfile.clear_cache()
2180
class _CommitBuilder(CommitBuilder):
2181
"""Temporary class so old CommitBuilders are detected properly
2183
Note: CommitBuilder works whether or not root entry is recorded.
2186
record_root_entry = True
2189
class RootCommitBuilder(CommitBuilder):
2190
"""This commitbuilder actually records the root id"""
2192
record_root_entry = True
2194
def record_entry_contents(self, ie, parent_invs, path, tree):
2195
"""Record the content of ie from tree into the commit if needed.
2197
Side effect: sets ie.revision when unchanged
2199
:param ie: An inventory entry present in the commit.
2200
:param parent_invs: The inventories of the parent revisions of the
2202
:param path: The path the entry is at in the tree.
2203
:param tree: The tree which contains this entry and should be used to
2206
assert self.new_inventory.root is not None or ie.parent_id is None
2207
self.new_inventory.add(ie)
2209
# ie.revision is always None if the InventoryEntry is considered
2210
# for committing. ie.snapshot will record the correct revision
2211
# which may be the sole parent if it is untouched.
2212
if ie.revision is not None:
2215
previous_entries = ie.find_previous_heads(
2217
self.repository.weave_store,
2218
self.repository.get_transaction())
2219
# we are creating a new revision for ie in the history store
2221
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2233
def _unescaper(match, _map=_unescape_map):
2234
code = match.group(1)
2238
if not code.startswith('#'):
2240
return unichr(int(code[1:])).encode('utf8')
2246
def _unescape_xml(data):
2247
"""Unescape predefined XML entities in a string of data."""
2249
if _unescape_re is None:
2250
_unescape_re = re.compile('\&([^;]*);')
2251
return _unescape_re.sub(_unescaper, data)