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.revisiontree import RevisionTree
44
from bzrlib.store.versioned import VersionedFileStore
45
from bzrlib.store.text import TextStore
46
from bzrlib.testament import Testament
50
from bzrlib.decorators import needs_read_lock, needs_write_lock
51
from bzrlib.inter import InterObject
52
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
53
from bzrlib.symbol_versioning import (
57
from bzrlib.trace import mutter, note, warning
60
# Old formats display a warning, but only once
61
_deprecation_warning_done = False
64
######################################################################
67
class Repository(object):
68
"""Repository holding history for one or more branches.
70
The repository holds and retrieves historical information including
71
revisions and file history. It's normally accessed only by the Branch,
72
which views a particular line of development through that history.
74
The Repository builds on top of Stores and a Transport, which respectively
75
describe the disk data format and the way of accessing the (possibly
79
_file_ids_altered_regex = lazy_regex.lazy_compile(
80
r'file_id="(?P<file_id>[^"]+)"'
81
r'.*revision="(?P<revision_id>[^"]+)"'
85
def add_inventory(self, revision_id, inv, parents):
86
"""Add the inventory inv to the repository as revision_id.
88
:param parents: The revision ids of the parents that revision_id
89
is known to have and are in the repository already.
91
returns the sha1 of the serialized inventory.
93
revision_id = osutils.safe_revision_id(revision_id)
94
_mod_revision.check_not_reserved_id(revision_id)
95
assert inv.revision_id is None or inv.revision_id == revision_id, \
96
"Mismatch between inventory revision" \
97
" id and insertion revid (%r, %r)" % (inv.revision_id, revision_id)
98
assert inv.root is not None
99
inv_text = self.serialise_inventory(inv)
100
inv_sha1 = osutils.sha_string(inv_text)
101
inv_vf = self.control_weaves.get_weave('inventory',
102
self.get_transaction())
103
self._inventory_add_lines(inv_vf, revision_id, parents,
104
osutils.split_lines(inv_text))
107
def _inventory_add_lines(self, inv_vf, revision_id, parents, lines):
109
for parent in parents:
111
final_parents.append(parent)
113
inv_vf.add_lines(revision_id, final_parents, lines)
116
def add_revision(self, revision_id, rev, inv=None, config=None):
117
"""Add rev to the revision store as revision_id.
119
:param revision_id: the revision id to use.
120
:param rev: The revision object.
121
:param inv: The inventory for the revision. if None, it will be looked
122
up in the inventory storer
123
:param config: If None no digital signature will be created.
124
If supplied its signature_needed method will be used
125
to determine if a signature should be made.
127
revision_id = osutils.safe_revision_id(revision_id)
128
# TODO: jam 20070210 Shouldn't we check rev.revision_id and
130
_mod_revision.check_not_reserved_id(revision_id)
131
if config is not None and config.signature_needed():
133
inv = self.get_inventory(revision_id)
134
plaintext = Testament(rev, inv).as_short_text()
135
self.store_revision_signature(
136
gpg.GPGStrategy(config), plaintext, revision_id)
137
if not revision_id in self.get_inventory_weave():
139
raise errors.WeaveRevisionNotPresent(revision_id,
140
self.get_inventory_weave())
142
# yes, this is not suitable for adding with ghosts.
143
self.add_inventory(revision_id, inv, rev.parent_ids)
144
self._revision_store.add_revision(rev, self.get_transaction())
147
def _all_possible_ids(self):
148
"""Return all the possible revisions that we could find."""
149
return self.get_inventory_weave().versions()
151
def all_revision_ids(self):
152
"""Returns a list of all the revision ids in the repository.
154
This is deprecated because code should generally work on the graph
155
reachable from a particular revision, and ignore any other revisions
156
that might be present. There is no direct replacement method.
158
return self._all_revision_ids()
161
def _all_revision_ids(self):
162
"""Returns a list of all the revision ids in the repository.
164
These are in as much topological order as the underlying store can
165
present: for weaves ghosts may lead to a lack of correctness until
166
the reweave updates the parents list.
168
if self._revision_store.text_store.listable():
169
return self._revision_store.all_revision_ids(self.get_transaction())
170
result = self._all_possible_ids()
171
# TODO: jam 20070210 Ensure that _all_possible_ids returns non-unicode
172
# ids. (It should, since _revision_store's API should change to
173
# return utf8 revision_ids)
174
return self._eliminate_revisions_not_present(result)
176
def break_lock(self):
177
"""Break a lock if one is present from another instance.
179
Uses the ui factory to ask for confirmation if the lock may be from
182
self.control_files.break_lock()
185
def _eliminate_revisions_not_present(self, revision_ids):
186
"""Check every revision id in revision_ids to see if we have it.
188
Returns a set of the present revisions.
191
for id in revision_ids:
192
if self.has_revision(id):
197
def create(a_bzrdir):
198
"""Construct the current default format repository in a_bzrdir."""
199
return RepositoryFormat.get_default_format().initialize(a_bzrdir)
201
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
202
"""instantiate a Repository.
204
:param _format: The format of the repository on disk.
205
:param a_bzrdir: The BzrDir of the repository.
207
In the future we will have a single api for all stores for
208
getting file texts, inventories and revisions, then
209
this construct will accept instances of those things.
211
super(Repository, self).__init__()
212
self._format = _format
213
# the following are part of the public API for Repository:
214
self.bzrdir = a_bzrdir
215
self.control_files = control_files
216
self._revision_store = _revision_store
217
self.text_store = text_store
218
# backwards compatibility
219
self.weave_store = text_store
220
# not right yet - should be more semantically clear ?
222
self.control_store = control_store
223
self.control_weaves = control_store
224
# TODO: make sure to construct the right store classes, etc, depending
225
# on whether escaping is required.
226
self._warn_if_deprecated()
229
return '%s(%r)' % (self.__class__.__name__,
230
self.bzrdir.transport.base)
233
return self.control_files.is_locked()
235
def lock_write(self, token=None):
236
"""Lock this repository for writing.
238
:param token: if this is already locked, then lock_write will fail
239
unless the token matches the existing lock.
240
:returns: a token if this instance supports tokens, otherwise None.
241
:raises TokenLockingNotSupported: when a token is given but this
242
instance doesn't support using token locks.
243
:raises MismatchedToken: if the specified token doesn't match the token
244
of the existing lock.
246
A token should be passed in if you know that you have locked the object
247
some other way, and need to synchronise this object's state with that
250
XXX: this docstring is duplicated in many places, e.g. lockable_files.py
252
return self.control_files.lock_write(token=token)
255
self.control_files.lock_read()
257
def get_physical_lock_status(self):
258
return self.control_files.get_physical_lock_status()
260
def leave_lock_in_place(self):
261
"""Tell this repository not to release the physical lock when this
264
If lock_write doesn't return a token, then this method is not supported.
266
self.control_files.leave_in_place()
268
def dont_leave_lock_in_place(self):
269
"""Tell this repository to release the physical lock when this
270
object is unlocked, even if it didn't originally acquire it.
272
If lock_write doesn't return a token, then this method is not supported.
274
self.control_files.dont_leave_in_place()
277
def gather_stats(self, revid=None, committers=None):
278
"""Gather statistics from a revision id.
280
:param revid: The revision id to gather statistics from, if None, then
281
no revision specific statistics are gathered.
282
:param committers: Optional parameter controlling whether to grab
283
a count of committers from the revision specific statistics.
284
:return: A dictionary of statistics. Currently this contains:
285
committers: The number of committers if requested.
286
firstrev: A tuple with timestamp, timezone for the penultimate left
287
most ancestor of revid, if revid is not the NULL_REVISION.
288
latestrev: A tuple with timestamp, timezone for revid, if revid is
289
not the NULL_REVISION.
290
revisions: The total revision count in the repository.
291
size: An estimate disk size of the repository in bytes.
294
if revid and committers:
295
result['committers'] = 0
296
if revid and revid != _mod_revision.NULL_REVISION:
298
all_committers = set()
299
revisions = self.get_ancestry(revid)
300
# pop the leading None
302
first_revision = None
304
# ignore the revisions in the middle - just grab first and last
305
revisions = revisions[0], revisions[-1]
306
for revision in self.get_revisions(revisions):
307
if not first_revision:
308
first_revision = revision
310
all_committers.add(revision.committer)
311
last_revision = revision
313
result['committers'] = len(all_committers)
314
result['firstrev'] = (first_revision.timestamp,
315
first_revision.timezone)
316
result['latestrev'] = (last_revision.timestamp,
317
last_revision.timezone)
319
# now gather global repository information
320
if self.bzrdir.root_transport.listable():
321
c, t = self._revision_store.total_size(self.get_transaction())
322
result['revisions'] = c
327
def missing_revision_ids(self, other, revision_id=None):
328
"""Return the revision ids that other has that this does not.
330
These are returned in topological order.
332
revision_id: only return revision ids included by revision_id.
334
revision_id = osutils.safe_revision_id(revision_id)
335
return InterRepository.get(other, self).missing_revision_ids(revision_id)
339
"""Open the repository rooted at base.
341
For instance, if the repository is at URL/.bzr/repository,
342
Repository.open(URL) -> a Repository instance.
344
control = bzrdir.BzrDir.open(base)
345
return control.open_repository()
347
def copy_content_into(self, destination, revision_id=None):
348
"""Make a complete copy of the content in self into destination.
350
This is a destructive operation! Do not use it on existing
353
revision_id = osutils.safe_revision_id(revision_id)
354
return InterRepository.get(self, destination).copy_content(revision_id)
356
def fetch(self, source, revision_id=None, pb=None):
357
"""Fetch the content required to construct revision_id from source.
359
If revision_id is None all content is copied.
361
revision_id = osutils.safe_revision_id(revision_id)
362
inter = InterRepository.get(source, self)
364
return inter.fetch(revision_id=revision_id, pb=pb)
365
except NotImplementedError:
366
raise errors.IncompatibleRepositories(source, self)
368
def get_commit_builder(self, branch, parents, config, timestamp=None,
369
timezone=None, committer=None, revprops=None,
371
"""Obtain a CommitBuilder for this repository.
373
:param branch: Branch to commit to.
374
:param parents: Revision ids of the parents of the new revision.
375
:param config: Configuration to use.
376
:param timestamp: Optional timestamp recorded for commit.
377
:param timezone: Optional timezone for timestamp.
378
:param committer: Optional committer to set for commit.
379
:param revprops: Optional dictionary of revision properties.
380
:param revision_id: Optional revision id.
382
revision_id = osutils.safe_revision_id(revision_id)
383
return _CommitBuilder(self, parents, config, timestamp, timezone,
384
committer, revprops, revision_id)
387
self.control_files.unlock()
390
def clone(self, a_bzrdir, revision_id=None):
391
"""Clone this repository into a_bzrdir using the current format.
393
Currently no check is made that the format of this repository and
394
the bzrdir format are compatible. FIXME RBC 20060201.
396
:return: The newly created destination repository.
398
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
399
# use target default format.
400
dest_repo = a_bzrdir.create_repository()
402
# Most control formats need the repository to be specifically
403
# created, but on some old all-in-one formats it's not needed
405
dest_repo = self._format.initialize(a_bzrdir, shared=self.is_shared())
406
except errors.UninitializableFormat:
407
dest_repo = a_bzrdir.open_repository()
408
self.copy_content_into(dest_repo, revision_id)
412
def has_revision(self, revision_id):
413
"""True if this repository has a copy of the revision."""
414
revision_id = osutils.safe_revision_id(revision_id)
415
return self._revision_store.has_revision_id(revision_id,
416
self.get_transaction())
419
def get_revision_reconcile(self, revision_id):
420
"""'reconcile' helper routine that allows access to a revision always.
422
This variant of get_revision does not cross check the weave graph
423
against the revision one as get_revision does: but it should only
424
be used by reconcile, or reconcile-alike commands that are correcting
425
or testing the revision graph.
427
if not revision_id or not isinstance(revision_id, basestring):
428
raise errors.InvalidRevisionId(revision_id=revision_id,
430
return self.get_revisions([revision_id])[0]
433
def get_revisions(self, revision_ids):
434
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
435
revs = self._revision_store.get_revisions(revision_ids,
436
self.get_transaction())
438
assert not isinstance(rev.revision_id, unicode)
439
for parent_id in rev.parent_ids:
440
assert not isinstance(parent_id, unicode)
444
def get_revision_xml(self, revision_id):
445
# TODO: jam 20070210 This shouldn't be necessary since get_revision
446
# would have already do it.
447
# TODO: jam 20070210 Just use _serializer.write_revision_to_string()
448
revision_id = osutils.safe_revision_id(revision_id)
449
rev = self.get_revision(revision_id)
451
# the current serializer..
452
self._revision_store._serializer.write_revision(rev, rev_tmp)
454
return rev_tmp.getvalue()
457
def get_revision(self, revision_id):
458
"""Return the Revision object for a named revision"""
459
# TODO: jam 20070210 get_revision_reconcile should do this for us
460
revision_id = osutils.safe_revision_id(revision_id)
461
r = self.get_revision_reconcile(revision_id)
462
# weave corruption can lead to absent revision markers that should be
464
# the following test is reasonably cheap (it needs a single weave read)
465
# and the weave is cached in read transactions. In write transactions
466
# it is not cached but typically we only read a small number of
467
# revisions. For knits when they are introduced we will probably want
468
# to ensure that caching write transactions are in use.
469
inv = self.get_inventory_weave()
470
self._check_revision_parents(r, inv)
474
def get_deltas_for_revisions(self, revisions):
475
"""Produce a generator of revision deltas.
477
Note that the input is a sequence of REVISIONS, not revision_ids.
478
Trees will be held in memory until the generator exits.
479
Each delta is relative to the revision's lefthand predecessor.
481
required_trees = set()
482
for revision in revisions:
483
required_trees.add(revision.revision_id)
484
required_trees.update(revision.parent_ids[:1])
485
trees = dict((t.get_revision_id(), t) for
486
t in self.revision_trees(required_trees))
487
for revision in revisions:
488
if not revision.parent_ids:
489
old_tree = self.revision_tree(None)
491
old_tree = trees[revision.parent_ids[0]]
492
yield trees[revision.revision_id].changes_from(old_tree)
495
def get_revision_delta(self, revision_id):
496
"""Return the delta for one revision.
498
The delta is relative to the left-hand predecessor of the
501
r = self.get_revision(revision_id)
502
return list(self.get_deltas_for_revisions([r]))[0]
504
def _check_revision_parents(self, revision, inventory):
505
"""Private to Repository and Fetch.
507
This checks the parentage of revision in an inventory weave for
508
consistency and is only applicable to inventory-weave-for-ancestry
509
using repository formats & fetchers.
511
weave_parents = inventory.get_parents(revision.revision_id)
512
weave_names = inventory.versions()
513
for parent_id in revision.parent_ids:
514
if parent_id in weave_names:
515
# this parent must not be a ghost.
516
if not parent_id in weave_parents:
518
raise errors.CorruptRepository(self)
521
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
522
revision_id = osutils.safe_revision_id(revision_id)
523
signature = gpg_strategy.sign(plaintext)
524
self._revision_store.add_revision_signature_text(revision_id,
526
self.get_transaction())
528
def fileids_altered_by_revision_ids(self, revision_ids):
529
"""Find the file ids and versions affected by revisions.
531
:param revisions: an iterable containing revision ids.
532
:return: a dictionary mapping altered file-ids to an iterable of
533
revision_ids. Each altered file-ids has the exact revision_ids that
534
altered it listed explicitly.
536
assert self._serializer.support_altered_by_hack, \
537
("fileids_altered_by_revision_ids only supported for branches "
538
"which store inventory as unnested xml, not on %r" % self)
539
selected_revision_ids = set(osutils.safe_revision_id(r)
540
for r in revision_ids)
541
w = self.get_inventory_weave()
544
# this code needs to read every new line in every inventory for the
545
# inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
546
# not present in one of those inventories is unnecessary but not
547
# harmful because we are filtering by the revision id marker in the
548
# inventory lines : we only select file ids altered in one of those
549
# revisions. We don't need to see all lines in the inventory because
550
# only those added in an inventory in rev X can contain a revision=X
552
unescape_revid_cache = {}
553
unescape_fileid_cache = {}
555
# jam 20061218 In a big fetch, this handles hundreds of thousands
556
# of lines, so it has had a lot of inlining and optimizing done.
557
# Sorry that it is a little bit messy.
558
# Move several functions to be local variables, since this is a long
560
search = self._file_ids_altered_regex.search
561
unescape = _unescape_xml
562
setdefault = result.setdefault
563
pb = ui.ui_factory.nested_progress_bar()
565
for line in w.iter_lines_added_or_present_in_versions(
566
selected_revision_ids, pb=pb):
570
# One call to match.group() returning multiple items is quite a
571
# bit faster than 2 calls to match.group() each returning 1
572
file_id, revision_id = match.group('file_id', 'revision_id')
574
# Inlining the cache lookups helps a lot when you make 170,000
575
# lines and 350k ids, versus 8.4 unique ids.
576
# Using a cache helps in 2 ways:
577
# 1) Avoids unnecessary decoding calls
578
# 2) Re-uses cached strings, which helps in future set and
580
# (2) is enough that removing encoding entirely along with
581
# the cache (so we are using plain strings) results in no
582
# performance improvement.
584
revision_id = unescape_revid_cache[revision_id]
586
unescaped = unescape(revision_id)
587
unescape_revid_cache[revision_id] = unescaped
588
revision_id = unescaped
590
if revision_id in selected_revision_ids:
592
file_id = unescape_fileid_cache[file_id]
594
unescaped = unescape(file_id)
595
unescape_fileid_cache[file_id] = unescaped
597
setdefault(file_id, set()).add(revision_id)
603
def get_inventory_weave(self):
604
return self.control_weaves.get_weave('inventory',
605
self.get_transaction())
608
def get_inventory(self, revision_id):
609
"""Get Inventory object by hash."""
610
# TODO: jam 20070210 Technically we don't need to sanitize, since all
611
# called functions must sanitize.
612
revision_id = osutils.safe_revision_id(revision_id)
613
return self.deserialise_inventory(
614
revision_id, self.get_inventory_xml(revision_id))
616
def deserialise_inventory(self, revision_id, xml):
617
"""Transform the xml into an inventory object.
619
:param revision_id: The expected revision id of the inventory.
620
:param xml: A serialised inventory.
622
revision_id = osutils.safe_revision_id(revision_id)
623
result = self._serializer.read_inventory_from_string(xml)
624
result.root.revision = revision_id
627
def serialise_inventory(self, inv):
628
return self._serializer.write_inventory_to_string(inv)
631
def get_inventory_xml(self, revision_id):
632
"""Get inventory XML as a file object."""
633
revision_id = osutils.safe_revision_id(revision_id)
635
assert isinstance(revision_id, str), type(revision_id)
636
iw = self.get_inventory_weave()
637
return iw.get_text(revision_id)
639
raise errors.HistoryMissing(self, 'inventory', revision_id)
642
def get_inventory_sha1(self, revision_id):
643
"""Return the sha1 hash of the inventory entry
645
# TODO: jam 20070210 Shouldn't this be deprecated / removed?
646
revision_id = osutils.safe_revision_id(revision_id)
647
return self.get_revision(revision_id).inventory_sha1
650
def get_revision_graph(self, revision_id=None):
651
"""Return a dictionary containing the revision graph.
653
:param revision_id: The revision_id to get a graph from. If None, then
654
the entire revision graph is returned. This is a deprecated mode of
655
operation and will be removed in the future.
656
:return: a dictionary of revision_id->revision_parents_list.
658
# special case NULL_REVISION
659
if revision_id == _mod_revision.NULL_REVISION:
661
revision_id = osutils.safe_revision_id(revision_id)
662
a_weave = self.get_inventory_weave()
663
all_revisions = self._eliminate_revisions_not_present(
665
entire_graph = dict([(node, a_weave.get_parents(node)) for
666
node in all_revisions])
667
if revision_id is None:
669
elif revision_id not in entire_graph:
670
raise errors.NoSuchRevision(self, revision_id)
672
# add what can be reached from revision_id
674
pending = set([revision_id])
675
while len(pending) > 0:
677
result[node] = entire_graph[node]
678
for revision_id in result[node]:
679
if revision_id not in result:
680
pending.add(revision_id)
684
def get_revision_graph_with_ghosts(self, revision_ids=None):
685
"""Return a graph of the revisions with ghosts marked as applicable.
687
:param revision_ids: an iterable of revisions to graph or None for all.
688
:return: a Graph object with the graph reachable from revision_ids.
690
result = graph.Graph()
692
pending = set(self.all_revision_ids())
695
pending = set(osutils.safe_revision_id(r) for r in revision_ids)
696
# special case NULL_REVISION
697
if _mod_revision.NULL_REVISION in pending:
698
pending.remove(_mod_revision.NULL_REVISION)
699
required = set(pending)
702
revision_id = pending.pop()
704
rev = self.get_revision(revision_id)
705
except errors.NoSuchRevision:
706
if revision_id in required:
709
result.add_ghost(revision_id)
711
for parent_id in rev.parent_ids:
712
# is this queued or done ?
713
if (parent_id not in pending and
714
parent_id not in done):
716
pending.add(parent_id)
717
result.add_node(revision_id, rev.parent_ids)
718
done.add(revision_id)
721
def _get_history_vf(self):
722
"""Get a versionedfile whose history graph reflects all revisions.
724
For weave repositories, this is the inventory weave.
726
return self.get_inventory_weave()
728
def iter_reverse_revision_history(self, revision_id):
729
"""Iterate backwards through revision ids in the lefthand history
731
:param revision_id: The revision id to start with. All its lefthand
732
ancestors will be traversed.
734
revision_id = osutils.safe_revision_id(revision_id)
735
if revision_id in (None, _mod_revision.NULL_REVISION):
737
next_id = revision_id
738
versionedfile = self._get_history_vf()
741
parents = versionedfile.get_parents(next_id)
742
if len(parents) == 0:
748
def get_revision_inventory(self, revision_id):
749
"""Return inventory of a past revision."""
750
# TODO: Unify this with get_inventory()
751
# bzr 0.0.6 and later imposes the constraint that the inventory_id
752
# must be the same as its revision, so this is trivial.
753
if revision_id is None:
754
# This does not make sense: if there is no revision,
755
# then it is the current tree inventory surely ?!
756
# and thus get_root_id() is something that looks at the last
757
# commit on the branch, and the get_root_id is an inventory check.
758
raise NotImplementedError
759
# return Inventory(self.get_root_id())
761
return self.get_inventory(revision_id)
765
"""Return True if this repository is flagged as a shared repository."""
766
raise NotImplementedError(self.is_shared)
769
def reconcile(self, other=None, thorough=False):
770
"""Reconcile this repository."""
771
from bzrlib.reconcile import RepoReconciler
772
reconciler = RepoReconciler(self, thorough=thorough)
773
reconciler.reconcile()
777
def revision_tree(self, revision_id):
778
"""Return Tree for a revision on this branch.
780
`revision_id` may be None for the empty tree revision.
782
# TODO: refactor this to use an existing revision object
783
# so we don't need to read it in twice.
784
if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
785
return RevisionTree(self, Inventory(root_id=None),
786
_mod_revision.NULL_REVISION)
788
revision_id = osutils.safe_revision_id(revision_id)
789
inv = self.get_revision_inventory(revision_id)
790
return RevisionTree(self, inv, revision_id)
793
def revision_trees(self, revision_ids):
794
"""Return Tree for a revision on this branch.
796
`revision_id` may not be None or 'null:'"""
797
assert None not in revision_ids
798
assert _mod_revision.NULL_REVISION not in revision_ids
799
texts = self.get_inventory_weave().get_texts(revision_ids)
800
for text, revision_id in zip(texts, revision_ids):
801
inv = self.deserialise_inventory(revision_id, text)
802
yield RevisionTree(self, inv, revision_id)
805
def get_ancestry(self, revision_id):
806
"""Return a list of revision-ids integrated by a revision.
808
The first element of the list is always None, indicating the origin
809
revision. This might change when we have history horizons, or
810
perhaps we should have a new API.
812
This is topologically sorted.
814
if revision_id is None:
816
revision_id = osutils.safe_revision_id(revision_id)
817
if not self.has_revision(revision_id):
818
raise errors.NoSuchRevision(self, revision_id)
819
w = self.get_inventory_weave()
820
candidates = w.get_ancestry(revision_id)
821
return [None] + candidates # self._eliminate_revisions_not_present(candidates)
824
def print_file(self, file, revision_id):
825
"""Print `file` to stdout.
827
FIXME RBC 20060125 as John Meinel points out this is a bad api
828
- it writes to stdout, it assumes that that is valid etc. Fix
829
by creating a new more flexible convenience function.
831
revision_id = osutils.safe_revision_id(revision_id)
832
tree = self.revision_tree(revision_id)
833
# use inventory as it was in that revision
834
file_id = tree.inventory.path2id(file)
836
# TODO: jam 20060427 Write a test for this code path
837
# it had a bug in it, and was raising the wrong
839
raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
840
tree.print_file(file_id)
842
def get_transaction(self):
843
return self.control_files.get_transaction()
845
def revision_parents(self, revision_id):
846
revision_id = osutils.safe_revision_id(revision_id)
847
return self.get_inventory_weave().parent_names(revision_id)
850
def set_make_working_trees(self, new_value):
851
"""Set the policy flag for making working trees when creating branches.
853
This only applies to branches that use this repository.
855
The default is 'True'.
856
:param new_value: True to restore the default, False to disable making
859
raise NotImplementedError(self.set_make_working_trees)
861
def make_working_trees(self):
862
"""Returns the policy for making working trees on new branches."""
863
raise NotImplementedError(self.make_working_trees)
866
def sign_revision(self, revision_id, gpg_strategy):
867
revision_id = osutils.safe_revision_id(revision_id)
868
plaintext = Testament.from_revision(self, revision_id).as_short_text()
869
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
872
def has_signature_for_revision_id(self, revision_id):
873
"""Query for a revision signature for revision_id in the repository."""
874
revision_id = osutils.safe_revision_id(revision_id)
875
return self._revision_store.has_signature(revision_id,
876
self.get_transaction())
879
def get_signature_text(self, revision_id):
880
"""Return the text for a signature."""
881
revision_id = osutils.safe_revision_id(revision_id)
882
return self._revision_store.get_signature_text(revision_id,
883
self.get_transaction())
886
def check(self, revision_ids):
887
"""Check consistency of all history of given revision_ids.
889
Different repository implementations should override _check().
891
:param revision_ids: A non-empty list of revision_ids whose ancestry
892
will be checked. Typically the last revision_id of a branch.
895
raise ValueError("revision_ids must be non-empty in %s.check"
897
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
898
return self._check(revision_ids)
900
def _check(self, revision_ids):
901
result = check.Check(self)
905
def _warn_if_deprecated(self):
906
global _deprecation_warning_done
907
if _deprecation_warning_done:
909
_deprecation_warning_done = True
910
warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
911
% (self._format, self.bzrdir.transport.base))
913
def supports_rich_root(self):
914
return self._format.rich_root_data
916
def _check_ascii_revisionid(self, revision_id, method):
917
"""Private helper for ascii-only repositories."""
918
# weave repositories refuse to store revisionids that are non-ascii.
919
if revision_id is not None:
920
# weaves require ascii revision ids.
921
if isinstance(revision_id, unicode):
923
revision_id.encode('ascii')
924
except UnicodeEncodeError:
925
raise errors.NonAsciiRevisionId(method, self)
928
revision_id.decode('ascii')
929
except UnicodeDecodeError:
930
raise errors.NonAsciiRevisionId(method, self)
934
# remove these delegates a while after bzr 0.15
935
def __make_delegated(name, from_module):
936
def _deprecated_repository_forwarder():
937
symbol_versioning.warn('%s moved to %s in bzr 0.15'
938
% (name, from_module),
941
m = __import__(from_module, globals(), locals(), [name])
943
return getattr(m, name)
944
except AttributeError:
945
raise AttributeError('module %s has no name %s'
947
globals()[name] = _deprecated_repository_forwarder
950
'AllInOneRepository',
951
'WeaveMetaDirRepository',
952
'PreSplitOutRepositoryFormat',
958
__make_delegated(_name, 'bzrlib.repofmt.weaverepo')
962
'RepositoryFormatKnit',
963
'RepositoryFormatKnit1',
965
__make_delegated(_name, 'bzrlib.repofmt.knitrepo')
968
def install_revision(repository, rev, revision_tree):
969
"""Install all revision data into a repository."""
972
for p_id in rev.parent_ids:
973
if repository.has_revision(p_id):
974
present_parents.append(p_id)
975
parent_trees[p_id] = repository.revision_tree(p_id)
977
parent_trees[p_id] = repository.revision_tree(None)
979
inv = revision_tree.inventory
980
entries = inv.iter_entries()
981
# backwards compatability hack: skip the root id.
982
if not repository.supports_rich_root():
983
path, root = entries.next()
984
if root.revision != rev.revision_id:
985
raise errors.IncompatibleRevision(repr(repository))
986
# Add the texts that are not already present
987
for path, ie in entries:
988
w = repository.weave_store.get_weave_or_empty(ie.file_id,
989
repository.get_transaction())
990
if ie.revision not in w:
992
# FIXME: TODO: The following loop *may* be overlapping/duplicate
993
# with InventoryEntry.find_previous_heads(). if it is, then there
994
# is a latent bug here where the parents may have ancestors of each
996
for revision, tree in parent_trees.iteritems():
997
if ie.file_id not in tree:
999
parent_id = tree.inventory[ie.file_id].revision
1000
if parent_id in text_parents:
1002
text_parents.append(parent_id)
1004
vfile = repository.weave_store.get_weave_or_empty(ie.file_id,
1005
repository.get_transaction())
1006
lines = revision_tree.get_file(ie.file_id).readlines()
1007
vfile.add_lines(rev.revision_id, text_parents, lines)
1009
# install the inventory
1010
repository.add_inventory(rev.revision_id, inv, present_parents)
1011
except errors.RevisionAlreadyPresent:
1013
repository.add_revision(rev.revision_id, rev, inv)
1016
class MetaDirRepository(Repository):
1017
"""Repositories in the new meta-dir layout."""
1019
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
1020
super(MetaDirRepository, self).__init__(_format,
1026
dir_mode = self.control_files._dir_mode
1027
file_mode = self.control_files._file_mode
1030
def is_shared(self):
1031
"""Return True if this repository is flagged as a shared repository."""
1032
return self.control_files._transport.has('shared-storage')
1035
def set_make_working_trees(self, new_value):
1036
"""Set the policy flag for making working trees when creating branches.
1038
This only applies to branches that use this repository.
1040
The default is 'True'.
1041
:param new_value: True to restore the default, False to disable making
1046
self.control_files._transport.delete('no-working-trees')
1047
except errors.NoSuchFile:
1050
self.control_files.put_utf8('no-working-trees', '')
1052
def make_working_trees(self):
1053
"""Returns the policy for making working trees on new branches."""
1054
return not self.control_files._transport.has('no-working-trees')
1057
class RepositoryFormatRegistry(registry.Registry):
1058
"""Registry of RepositoryFormats.
1061
def get(self, format_string):
1062
r = registry.Registry.get(self, format_string)
1068
format_registry = RepositoryFormatRegistry()
1069
"""Registry of formats, indexed by their identifying format string.
1071
This can contain either format instances themselves, or classes/factories that
1072
can be called to obtain one.
1076
#####################################################################
1077
# Repository Formats
1079
class RepositoryFormat(object):
1080
"""A repository format.
1082
Formats provide three things:
1083
* An initialization routine to construct repository data on disk.
1084
* a format string which is used when the BzrDir supports versioned
1086
* an open routine which returns a Repository instance.
1088
Formats are placed in an dict by their format string for reference
1089
during opening. These should be subclasses of RepositoryFormat
1092
Once a format is deprecated, just deprecate the initialize and open
1093
methods on the format class. Do not deprecate the object, as the
1094
object will be created every system load.
1096
Common instance attributes:
1097
_matchingbzrdir - the bzrdir format that the repository format was
1098
originally written to work with. This can be used if manually
1099
constructing a bzrdir and repository, or more commonly for test suite
1104
return "<%s>" % self.__class__.__name__
1106
def __eq__(self, other):
1107
# format objects are generally stateless
1108
return isinstance(other, self.__class__)
1110
def __ne__(self, other):
1111
return not self == other
1114
def find_format(klass, a_bzrdir):
1115
"""Return the format for the repository object in a_bzrdir.
1117
This is used by bzr native formats that have a "format" file in
1118
the repository. Other methods may be used by different types of
1122
transport = a_bzrdir.get_repository_transport(None)
1123
format_string = transport.get("format").read()
1124
return format_registry.get(format_string)
1125
except errors.NoSuchFile:
1126
raise errors.NoRepositoryPresent(a_bzrdir)
1128
raise errors.UnknownFormatError(format=format_string)
1131
def register_format(klass, format):
1132
format_registry.register(format.get_format_string(), format)
1135
def unregister_format(klass, format):
1136
format_registry.remove(format.get_format_string())
1139
def get_default_format(klass):
1140
"""Return the current default format."""
1141
from bzrlib import bzrdir
1142
return bzrdir.format_registry.make_bzrdir('default').repository_format
1144
def _get_control_store(self, repo_transport, control_files):
1145
"""Return the control store for this repository."""
1146
raise NotImplementedError(self._get_control_store)
1148
def get_format_string(self):
1149
"""Return the ASCII format string that identifies this format.
1151
Note that in pre format ?? repositories the format string is
1152
not permitted nor written to disk.
1154
raise NotImplementedError(self.get_format_string)
1156
def get_format_description(self):
1157
"""Return the short description for this format."""
1158
raise NotImplementedError(self.get_format_description)
1160
def _get_revision_store(self, repo_transport, control_files):
1161
"""Return the revision store object for this a_bzrdir."""
1162
raise NotImplementedError(self._get_revision_store)
1164
def _get_text_rev_store(self,
1171
"""Common logic for getting a revision store for a repository.
1173
see self._get_revision_store for the subclass-overridable method to
1174
get the store for a repository.
1176
from bzrlib.store.revision.text import TextRevisionStore
1177
dir_mode = control_files._dir_mode
1178
file_mode = control_files._file_mode
1179
text_store = TextStore(transport.clone(name),
1181
compressed=compressed,
1183
file_mode=file_mode)
1184
_revision_store = TextRevisionStore(text_store, serializer)
1185
return _revision_store
1187
# TODO: this shouldn't be in the base class, it's specific to things that
1188
# use weaves or knits -- mbp 20070207
1189
def _get_versioned_file_store(self,
1194
versionedfile_class=None,
1195
versionedfile_kwargs={},
1197
if versionedfile_class is None:
1198
versionedfile_class = self._versionedfile_class
1199
weave_transport = control_files._transport.clone(name)
1200
dir_mode = control_files._dir_mode
1201
file_mode = control_files._file_mode
1202
return VersionedFileStore(weave_transport, prefixed=prefixed,
1204
file_mode=file_mode,
1205
versionedfile_class=versionedfile_class,
1206
versionedfile_kwargs=versionedfile_kwargs,
1209
def initialize(self, a_bzrdir, shared=False):
1210
"""Initialize a repository of this format in a_bzrdir.
1212
:param a_bzrdir: The bzrdir to put the new repository in it.
1213
:param shared: The repository should be initialized as a sharable one.
1214
:returns: The new repository object.
1216
This may raise UninitializableFormat if shared repository are not
1217
compatible the a_bzrdir.
1219
raise NotImplementedError(self.initialize)
1221
def is_supported(self):
1222
"""Is this format supported?
1224
Supported formats must be initializable and openable.
1225
Unsupported formats may not support initialization or committing or
1226
some other features depending on the reason for not being supported.
1230
def check_conversion_target(self, target_format):
1231
raise NotImplementedError(self.check_conversion_target)
1233
def open(self, a_bzrdir, _found=False):
1234
"""Return an instance of this format for the bzrdir a_bzrdir.
1236
_found is a private parameter, do not use it.
1238
raise NotImplementedError(self.open)
1241
class MetaDirRepositoryFormat(RepositoryFormat):
1242
"""Common base class for the new repositories using the metadir layout."""
1244
rich_root_data = False
1245
supports_tree_reference = False
1246
_matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1249
super(MetaDirRepositoryFormat, self).__init__()
1251
def _create_control_files(self, a_bzrdir):
1252
"""Create the required files and the initial control_files object."""
1253
# FIXME: RBC 20060125 don't peek under the covers
1254
# NB: no need to escape relative paths that are url safe.
1255
repository_transport = a_bzrdir.get_repository_transport(self)
1256
control_files = lockable_files.LockableFiles(repository_transport,
1257
'lock', lockdir.LockDir)
1258
control_files.create_lock()
1259
return control_files
1261
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1262
"""Upload the initial blank content."""
1263
control_files = self._create_control_files(a_bzrdir)
1264
control_files.lock_write()
1266
control_files._transport.mkdir_multi(dirs,
1267
mode=control_files._dir_mode)
1268
for file, content in files:
1269
control_files.put(file, content)
1270
for file, content in utf8_files:
1271
control_files.put_utf8(file, content)
1273
control_files.put_utf8('shared-storage', '')
1275
control_files.unlock()
1278
# formats which have no format string are not discoverable
1279
# and not independently creatable, so are not registered. They're
1280
# all in bzrlib.repofmt.weaverepo now. When an instance of one of these is
1281
# needed, it's constructed directly by the BzrDir. Non-native formats where
1282
# the repository is not separately opened are similar.
1284
format_registry.register_lazy(
1285
'Bazaar-NG Repository format 7',
1286
'bzrlib.repofmt.weaverepo',
1289
# KEEP in sync with bzrdir.format_registry default, which controls the overall
1290
# default control directory format
1292
format_registry.register_lazy(
1293
'Bazaar-NG Knit Repository Format 1',
1294
'bzrlib.repofmt.knitrepo',
1295
'RepositoryFormatKnit1',
1297
format_registry.default_key = 'Bazaar-NG Knit Repository Format 1'
1299
format_registry.register_lazy(
1300
'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
1301
'bzrlib.repofmt.knitrepo',
1302
'RepositoryFormatKnit3',
1306
class InterRepository(InterObject):
1307
"""This class represents operations taking place between two repositories.
1309
Its instances have methods like copy_content and fetch, and contain
1310
references to the source and target repositories these operations can be
1313
Often we will provide convenience methods on 'repository' which carry out
1314
operations with another repository - they will always forward to
1315
InterRepository.get(other).method_name(parameters).
1319
"""The available optimised InterRepository types."""
1321
def copy_content(self, revision_id=None):
1322
raise NotImplementedError(self.copy_content)
1324
def fetch(self, revision_id=None, pb=None):
1325
"""Fetch the content required to construct revision_id.
1327
The content is copied from self.source to self.target.
1329
:param revision_id: if None all content is copied, if NULL_REVISION no
1331
:param pb: optional progress bar to use for progress reports. If not
1332
provided a default one will be created.
1334
Returns the copied revision count and the failed revisions in a tuple:
1337
raise NotImplementedError(self.fetch)
1340
def missing_revision_ids(self, revision_id=None):
1341
"""Return the revision ids that source has that target does not.
1343
These are returned in topological order.
1345
:param revision_id: only return revision ids included by this
1348
# generic, possibly worst case, slow code path.
1349
target_ids = set(self.target.all_revision_ids())
1350
if revision_id is not None:
1351
# TODO: jam 20070210 InterRepository is internal enough that it
1352
# should assume revision_ids are already utf-8
1353
revision_id = osutils.safe_revision_id(revision_id)
1354
source_ids = self.source.get_ancestry(revision_id)
1355
assert source_ids[0] is None
1358
source_ids = self.source.all_revision_ids()
1359
result_set = set(source_ids).difference(target_ids)
1360
# this may look like a no-op: its not. It preserves the ordering
1361
# other_ids had while only returning the members from other_ids
1362
# that we've decided we need.
1363
return [rev_id for rev_id in source_ids if rev_id in result_set]
1366
class InterSameDataRepository(InterRepository):
1367
"""Code for converting between repositories that represent the same data.
1369
Data format and model must match for this to work.
1373
def _get_repo_format_to_test(self):
1374
"""Repository format for testing with."""
1375
return RepositoryFormat.get_default_format()
1378
def is_compatible(source, target):
1379
if source.supports_rich_root() != target.supports_rich_root():
1381
if source._serializer != target._serializer:
1386
def copy_content(self, revision_id=None):
1387
"""Make a complete copy of the content in self into destination.
1389
This is a destructive operation! Do not use it on existing
1392
:param revision_id: Only copy the content needed to construct
1393
revision_id and its parents.
1396
self.target.set_make_working_trees(self.source.make_working_trees())
1397
except NotImplementedError:
1399
# TODO: jam 20070210 This is fairly internal, so we should probably
1400
# just assert that revision_id is not unicode.
1401
revision_id = osutils.safe_revision_id(revision_id)
1402
# but don't bother fetching if we have the needed data now.
1403
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1404
self.target.has_revision(revision_id)):
1406
self.target.fetch(self.source, revision_id=revision_id)
1409
def fetch(self, revision_id=None, pb=None):
1410
"""See InterRepository.fetch()."""
1411
from bzrlib.fetch import GenericRepoFetcher
1412
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1413
self.source, self.source._format, self.target,
1414
self.target._format)
1415
# TODO: jam 20070210 This should be an assert, not a translate
1416
revision_id = osutils.safe_revision_id(revision_id)
1417
f = GenericRepoFetcher(to_repository=self.target,
1418
from_repository=self.source,
1419
last_revision=revision_id,
1421
return f.count_copied, f.failed_revisions
1424
class InterWeaveRepo(InterSameDataRepository):
1425
"""Optimised code paths between Weave based repositories."""
1428
def _get_repo_format_to_test(self):
1429
from bzrlib.repofmt import weaverepo
1430
return weaverepo.RepositoryFormat7()
1433
def is_compatible(source, target):
1434
"""Be compatible with known Weave formats.
1436
We don't test for the stores being of specific types because that
1437
could lead to confusing results, and there is no need to be
1440
from bzrlib.repofmt.weaverepo import (
1446
return (isinstance(source._format, (RepositoryFormat5,
1448
RepositoryFormat7)) and
1449
isinstance(target._format, (RepositoryFormat5,
1451
RepositoryFormat7)))
1452
except AttributeError:
1456
def copy_content(self, revision_id=None):
1457
"""See InterRepository.copy_content()."""
1458
# weave specific optimised path:
1459
# TODO: jam 20070210 Internal, should be an assert, not translate
1460
revision_id = osutils.safe_revision_id(revision_id)
1462
self.target.set_make_working_trees(self.source.make_working_trees())
1463
except NotImplementedError:
1465
# FIXME do not peek!
1466
if self.source.control_files._transport.listable():
1467
pb = ui.ui_factory.nested_progress_bar()
1469
self.target.weave_store.copy_all_ids(
1470
self.source.weave_store,
1472
from_transaction=self.source.get_transaction(),
1473
to_transaction=self.target.get_transaction())
1474
pb.update('copying inventory', 0, 1)
1475
self.target.control_weaves.copy_multi(
1476
self.source.control_weaves, ['inventory'],
1477
from_transaction=self.source.get_transaction(),
1478
to_transaction=self.target.get_transaction())
1479
self.target._revision_store.text_store.copy_all_ids(
1480
self.source._revision_store.text_store,
1485
self.target.fetch(self.source, revision_id=revision_id)
1488
def fetch(self, revision_id=None, pb=None):
1489
"""See InterRepository.fetch()."""
1490
from bzrlib.fetch import GenericRepoFetcher
1491
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1492
self.source, self.source._format, self.target, self.target._format)
1493
# TODO: jam 20070210 This should be an assert, not a translate
1494
revision_id = osutils.safe_revision_id(revision_id)
1495
f = GenericRepoFetcher(to_repository=self.target,
1496
from_repository=self.source,
1497
last_revision=revision_id,
1499
return f.count_copied, f.failed_revisions
1502
def missing_revision_ids(self, revision_id=None):
1503
"""See InterRepository.missing_revision_ids()."""
1504
# we want all revisions to satisfy revision_id in source.
1505
# but we don't want to stat every file here and there.
1506
# we want then, all revisions other needs to satisfy revision_id
1507
# checked, but not those that we have locally.
1508
# so the first thing is to get a subset of the revisions to
1509
# satisfy revision_id in source, and then eliminate those that
1510
# we do already have.
1511
# this is slow on high latency connection to self, but as as this
1512
# disk format scales terribly for push anyway due to rewriting
1513
# inventory.weave, this is considered acceptable.
1515
if revision_id is not None:
1516
source_ids = self.source.get_ancestry(revision_id)
1517
assert source_ids[0] is None
1520
source_ids = self.source._all_possible_ids()
1521
source_ids_set = set(source_ids)
1522
# source_ids is the worst possible case we may need to pull.
1523
# now we want to filter source_ids against what we actually
1524
# have in target, but don't try to check for existence where we know
1525
# we do not have a revision as that would be pointless.
1526
target_ids = set(self.target._all_possible_ids())
1527
possibly_present_revisions = target_ids.intersection(source_ids_set)
1528
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1529
required_revisions = source_ids_set.difference(actually_present_revisions)
1530
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1531
if revision_id is not None:
1532
# we used get_ancestry to determine source_ids then we are assured all
1533
# revisions referenced are present as they are installed in topological order.
1534
# and the tip revision was validated by get_ancestry.
1535
return required_topo_revisions
1537
# if we just grabbed the possibly available ids, then
1538
# we only have an estimate of whats available and need to validate
1539
# that against the revision records.
1540
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1543
class InterKnitRepo(InterSameDataRepository):
1544
"""Optimised code paths between Knit based repositories."""
1547
def _get_repo_format_to_test(self):
1548
from bzrlib.repofmt import knitrepo
1549
return knitrepo.RepositoryFormatKnit1()
1552
def is_compatible(source, target):
1553
"""Be compatible with known Knit formats.
1555
We don't test for the stores being of specific types because that
1556
could lead to confusing results, and there is no need to be
1559
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1
1561
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1562
isinstance(target._format, (RepositoryFormatKnit1)))
1563
except AttributeError:
1567
def fetch(self, revision_id=None, pb=None):
1568
"""See InterRepository.fetch()."""
1569
from bzrlib.fetch import KnitRepoFetcher
1570
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1571
self.source, self.source._format, self.target, self.target._format)
1572
# TODO: jam 20070210 This should be an assert, not a translate
1573
revision_id = osutils.safe_revision_id(revision_id)
1574
f = KnitRepoFetcher(to_repository=self.target,
1575
from_repository=self.source,
1576
last_revision=revision_id,
1578
return f.count_copied, f.failed_revisions
1581
def missing_revision_ids(self, revision_id=None):
1582
"""See InterRepository.missing_revision_ids()."""
1583
if revision_id is not None:
1584
source_ids = self.source.get_ancestry(revision_id)
1585
assert source_ids[0] is None
1588
source_ids = self.source._all_possible_ids()
1589
source_ids_set = set(source_ids)
1590
# source_ids is the worst possible case we may need to pull.
1591
# now we want to filter source_ids against what we actually
1592
# have in target, but don't try to check for existence where we know
1593
# we do not have a revision as that would be pointless.
1594
target_ids = set(self.target._all_possible_ids())
1595
possibly_present_revisions = target_ids.intersection(source_ids_set)
1596
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1597
required_revisions = source_ids_set.difference(actually_present_revisions)
1598
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1599
if revision_id is not None:
1600
# we used get_ancestry to determine source_ids then we are assured all
1601
# revisions referenced are present as they are installed in topological order.
1602
# and the tip revision was validated by get_ancestry.
1603
return required_topo_revisions
1605
# if we just grabbed the possibly available ids, then
1606
# we only have an estimate of whats available and need to validate
1607
# that against the revision records.
1608
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1611
class InterModel1and2(InterRepository):
1614
def _get_repo_format_to_test(self):
1618
def is_compatible(source, target):
1619
if not source.supports_rich_root() and target.supports_rich_root():
1625
def fetch(self, revision_id=None, pb=None):
1626
"""See InterRepository.fetch()."""
1627
from bzrlib.fetch import Model1toKnit2Fetcher
1628
# TODO: jam 20070210 This should be an assert, not a translate
1629
revision_id = osutils.safe_revision_id(revision_id)
1630
f = Model1toKnit2Fetcher(to_repository=self.target,
1631
from_repository=self.source,
1632
last_revision=revision_id,
1634
return f.count_copied, f.failed_revisions
1637
def copy_content(self, revision_id=None):
1638
"""Make a complete copy of the content in self into destination.
1640
This is a destructive operation! Do not use it on existing
1643
:param revision_id: Only copy the content needed to construct
1644
revision_id and its parents.
1647
self.target.set_make_working_trees(self.source.make_working_trees())
1648
except NotImplementedError:
1650
# TODO: jam 20070210 Internal, assert, don't translate
1651
revision_id = osutils.safe_revision_id(revision_id)
1652
# but don't bother fetching if we have the needed data now.
1653
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1654
self.target.has_revision(revision_id)):
1656
self.target.fetch(self.source, revision_id=revision_id)
1659
class InterKnit1and2(InterKnitRepo):
1662
def _get_repo_format_to_test(self):
1666
def is_compatible(source, target):
1667
"""Be compatible with Knit1 source and Knit3 target"""
1668
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit3
1670
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1, \
1671
RepositoryFormatKnit3
1672
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1673
isinstance(target._format, (RepositoryFormatKnit3)))
1674
except AttributeError:
1678
def fetch(self, revision_id=None, pb=None):
1679
"""See InterRepository.fetch()."""
1680
from bzrlib.fetch import Knit1to2Fetcher
1681
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1682
self.source, self.source._format, self.target,
1683
self.target._format)
1684
# TODO: jam 20070210 This should be an assert, not a translate
1685
revision_id = osutils.safe_revision_id(revision_id)
1686
f = Knit1to2Fetcher(to_repository=self.target,
1687
from_repository=self.source,
1688
last_revision=revision_id,
1690
return f.count_copied, f.failed_revisions
1693
class InterRemoteRepository(InterRepository):
1694
"""Code for converting between RemoteRepository objects.
1696
This just gets an non-remote repository from the RemoteRepository, and calls
1697
InterRepository.get again.
1700
def __init__(self, source, target):
1701
if isinstance(source, remote.RemoteRepository):
1702
source._ensure_real()
1703
real_source = source._real_repository
1705
real_source = source
1706
if isinstance(target, remote.RemoteRepository):
1707
target._ensure_real()
1708
real_target = target._real_repository
1710
real_target = target
1711
self.real_inter = InterRepository.get(real_source, real_target)
1714
def is_compatible(source, target):
1715
if isinstance(source, remote.RemoteRepository):
1717
if isinstance(target, remote.RemoteRepository):
1721
def copy_content(self, revision_id=None):
1722
self.real_inter.copy_content(revision_id=revision_id)
1724
def fetch(self, revision_id=None, pb=None):
1725
self.real_inter.fetch(revision_id=revision_id, pb=pb)
1728
def _get_repo_format_to_test(self):
1732
InterRepository.register_optimiser(InterSameDataRepository)
1733
InterRepository.register_optimiser(InterWeaveRepo)
1734
InterRepository.register_optimiser(InterKnitRepo)
1735
InterRepository.register_optimiser(InterModel1and2)
1736
InterRepository.register_optimiser(InterKnit1and2)
1737
InterRepository.register_optimiser(InterRemoteRepository)
1740
class RepositoryTestProviderAdapter(object):
1741
"""A tool to generate a suite testing multiple repository formats at once.
1743
This is done by copying the test once for each transport and injecting
1744
the transport_server, transport_readonly_server, and bzrdir_format and
1745
repository_format classes into each copy. Each copy is also given a new id()
1746
to make it easy to identify.
1749
def __init__(self, transport_server, transport_readonly_server, formats,
1750
vfs_transport_factory=None):
1751
self._transport_server = transport_server
1752
self._transport_readonly_server = transport_readonly_server
1753
self._vfs_transport_factory = vfs_transport_factory
1754
self._formats = formats
1756
def adapt(self, test):
1757
result = unittest.TestSuite()
1758
for repository_format, bzrdir_format in self._formats:
1759
from copy import deepcopy
1760
new_test = deepcopy(test)
1761
new_test.transport_server = self._transport_server
1762
new_test.transport_readonly_server = self._transport_readonly_server
1763
# Only override the test's vfs_transport_factory if one was
1764
# specified, otherwise just leave the default in place.
1765
if self._vfs_transport_factory:
1766
new_test.vfs_transport_factory = self._vfs_transport_factory
1767
new_test.bzrdir_format = bzrdir_format
1768
new_test.repository_format = repository_format
1769
def make_new_test_id():
1770
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1771
return lambda: new_id
1772
new_test.id = make_new_test_id()
1773
result.addTest(new_test)
1777
class InterRepositoryTestProviderAdapter(object):
1778
"""A tool to generate a suite testing multiple inter repository formats.
1780
This is done by copying the test once for each interrepo provider and injecting
1781
the transport_server, transport_readonly_server, repository_format and
1782
repository_to_format classes into each copy.
1783
Each copy is also given a new id() to make it easy to identify.
1786
def __init__(self, transport_server, transport_readonly_server, formats):
1787
self._transport_server = transport_server
1788
self._transport_readonly_server = transport_readonly_server
1789
self._formats = formats
1791
def adapt(self, test):
1792
result = unittest.TestSuite()
1793
for interrepo_class, repository_format, repository_format_to in self._formats:
1794
from copy import deepcopy
1795
new_test = deepcopy(test)
1796
new_test.transport_server = self._transport_server
1797
new_test.transport_readonly_server = self._transport_readonly_server
1798
new_test.interrepo_class = interrepo_class
1799
new_test.repository_format = repository_format
1800
new_test.repository_format_to = repository_format_to
1801
def make_new_test_id():
1802
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1803
return lambda: new_id
1804
new_test.id = make_new_test_id()
1805
result.addTest(new_test)
1809
def default_test_list():
1810
"""Generate the default list of interrepo permutations to test."""
1811
from bzrlib.repofmt import knitrepo, weaverepo
1813
# test the default InterRepository between format 6 and the current
1815
# XXX: robertc 20060220 reinstate this when there are two supported
1816
# formats which do not have an optimal code path between them.
1817
#result.append((InterRepository,
1818
# RepositoryFormat6(),
1819
# RepositoryFormatKnit1()))
1820
for optimiser_class in InterRepository._optimisers:
1821
format_to_test = optimiser_class._get_repo_format_to_test()
1822
if format_to_test is not None:
1823
result.append((optimiser_class,
1824
format_to_test, format_to_test))
1825
# if there are specific combinations we want to use, we can add them
1827
result.append((InterModel1and2,
1828
weaverepo.RepositoryFormat5(),
1829
knitrepo.RepositoryFormatKnit3()))
1830
result.append((InterKnit1and2,
1831
knitrepo.RepositoryFormatKnit1(),
1832
knitrepo.RepositoryFormatKnit3()))
1836
class CopyConverter(object):
1837
"""A repository conversion tool which just performs a copy of the content.
1839
This is slow but quite reliable.
1842
def __init__(self, target_format):
1843
"""Create a CopyConverter.
1845
:param target_format: The format the resulting repository should be.
1847
self.target_format = target_format
1849
def convert(self, repo, pb):
1850
"""Perform the conversion of to_convert, giving feedback via pb.
1852
:param to_convert: The disk object to convert.
1853
:param pb: a progress bar to use for progress information.
1858
# this is only useful with metadir layouts - separated repo content.
1859
# trigger an assertion if not such
1860
repo._format.get_format_string()
1861
self.repo_dir = repo.bzrdir
1862
self.step('Moving repository to repository.backup')
1863
self.repo_dir.transport.move('repository', 'repository.backup')
1864
backup_transport = self.repo_dir.transport.clone('repository.backup')
1865
repo._format.check_conversion_target(self.target_format)
1866
self.source_repo = repo._format.open(self.repo_dir,
1868
_override_transport=backup_transport)
1869
self.step('Creating new repository')
1870
converted = self.target_format.initialize(self.repo_dir,
1871
self.source_repo.is_shared())
1872
converted.lock_write()
1874
self.step('Copying content into repository.')
1875
self.source_repo.copy_content_into(converted)
1878
self.step('Deleting old repository content.')
1879
self.repo_dir.transport.delete_tree('repository.backup')
1880
self.pb.note('repository converted')
1882
def step(self, message):
1883
"""Update the pb by a step."""
1885
self.pb.update(message, self.count, self.total)
1888
class CommitBuilder(object):
1889
"""Provides an interface to build up a commit.
1891
This allows describing a tree to be committed without needing to
1892
know the internals of the format of the repository.
1895
record_root_entry = False
1896
def __init__(self, repository, parents, config, timestamp=None,
1897
timezone=None, committer=None, revprops=None,
1899
"""Initiate a CommitBuilder.
1901
:param repository: Repository to commit to.
1902
:param parents: Revision ids of the parents of the new revision.
1903
:param config: Configuration to use.
1904
:param timestamp: Optional timestamp recorded for commit.
1905
:param timezone: Optional timezone for timestamp.
1906
:param committer: Optional committer to set for commit.
1907
:param revprops: Optional dictionary of revision properties.
1908
:param revision_id: Optional revision id.
1910
self._config = config
1912
if committer is None:
1913
self._committer = self._config.username()
1915
assert isinstance(committer, basestring), type(committer)
1916
self._committer = committer
1918
self.new_inventory = Inventory(None)
1919
self._new_revision_id = osutils.safe_revision_id(revision_id)
1920
self.parents = parents
1921
self.repository = repository
1924
if revprops is not None:
1925
self._revprops.update(revprops)
1927
if timestamp is None:
1928
timestamp = time.time()
1929
# Restrict resolution to 1ms
1930
self._timestamp = round(timestamp, 3)
1932
if timezone is None:
1933
self._timezone = osutils.local_time_offset()
1935
self._timezone = int(timezone)
1937
self._generate_revision_if_needed()
1939
def commit(self, message):
1940
"""Make the actual commit.
1942
:return: The revision id of the recorded revision.
1944
rev = _mod_revision.Revision(
1945
timestamp=self._timestamp,
1946
timezone=self._timezone,
1947
committer=self._committer,
1949
inventory_sha1=self.inv_sha1,
1950
revision_id=self._new_revision_id,
1951
properties=self._revprops)
1952
rev.parent_ids = self.parents
1953
self.repository.add_revision(self._new_revision_id, rev,
1954
self.new_inventory, self._config)
1955
return self._new_revision_id
1957
def revision_tree(self):
1958
"""Return the tree that was just committed.
1960
After calling commit() this can be called to get a RevisionTree
1961
representing the newly committed tree. This is preferred to
1962
calling Repository.revision_tree() because that may require
1963
deserializing the inventory, while we already have a copy in
1966
return RevisionTree(self.repository, self.new_inventory,
1967
self._new_revision_id)
1969
def finish_inventory(self):
1970
"""Tell the builder that the inventory is finished."""
1971
if self.new_inventory.root is None:
1972
symbol_versioning.warn('Root entry should be supplied to'
1973
' record_entry_contents, as of bzr 0.10.',
1974
DeprecationWarning, stacklevel=2)
1975
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
1976
self.new_inventory.revision_id = self._new_revision_id
1977
self.inv_sha1 = self.repository.add_inventory(
1978
self._new_revision_id,
1983
def _gen_revision_id(self):
1984
"""Return new revision-id."""
1985
return generate_ids.gen_revision_id(self._config.username(),
1988
def _generate_revision_if_needed(self):
1989
"""Create a revision id if None was supplied.
1991
If the repository can not support user-specified revision ids
1992
they should override this function and raise CannotSetRevisionId
1993
if _new_revision_id is not None.
1995
:raises: CannotSetRevisionId
1997
if self._new_revision_id is None:
1998
self._new_revision_id = self._gen_revision_id()
2000
def record_entry_contents(self, ie, parent_invs, path, tree):
2001
"""Record the content of ie from tree into the commit if needed.
2003
Side effect: sets ie.revision when unchanged
2005
:param ie: An inventory entry present in the commit.
2006
:param parent_invs: The inventories of the parent revisions of the
2008
:param path: The path the entry is at in the tree.
2009
:param tree: The tree which contains this entry and should be used to
2012
if self.new_inventory.root is None and ie.parent_id is not None:
2013
symbol_versioning.warn('Root entry should be supplied to'
2014
' record_entry_contents, as of bzr 0.10.',
2015
DeprecationWarning, stacklevel=2)
2016
self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
2018
self.new_inventory.add(ie)
2020
# ie.revision is always None if the InventoryEntry is considered
2021
# for committing. ie.snapshot will record the correct revision
2022
# which may be the sole parent if it is untouched.
2023
if ie.revision is not None:
2026
# In this revision format, root entries have no knit or weave
2027
if ie is self.new_inventory.root:
2028
# When serializing out to disk and back in
2029
# root.revision is always _new_revision_id
2030
ie.revision = self._new_revision_id
2032
previous_entries = ie.find_previous_heads(
2034
self.repository.weave_store,
2035
self.repository.get_transaction())
2036
# we are creating a new revision for ie in the history store
2038
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2040
def modified_directory(self, file_id, file_parents):
2041
"""Record the presence of a symbolic link.
2043
:param file_id: The file_id of the link to record.
2044
:param file_parents: The per-file parent revision ids.
2046
self._add_text_to_weave(file_id, [], file_parents.keys())
2048
def modified_reference(self, file_id, file_parents):
2049
"""Record the modification of a reference.
2051
:param file_id: The file_id of the link to record.
2052
:param file_parents: The per-file parent revision ids.
2054
self._add_text_to_weave(file_id, [], file_parents.keys())
2056
def modified_file_text(self, file_id, file_parents,
2057
get_content_byte_lines, text_sha1=None,
2059
"""Record the text of file file_id
2061
:param file_id: The file_id of the file to record the text of.
2062
:param file_parents: The per-file parent revision ids.
2063
:param get_content_byte_lines: A callable which will return the byte
2065
:param text_sha1: Optional SHA1 of the file contents.
2066
:param text_size: Optional size of the file contents.
2068
# mutter('storing text of file {%s} in revision {%s} into %r',
2069
# file_id, self._new_revision_id, self.repository.weave_store)
2070
# special case to avoid diffing on renames or
2072
if (len(file_parents) == 1
2073
and text_sha1 == file_parents.values()[0].text_sha1
2074
and text_size == file_parents.values()[0].text_size):
2075
previous_ie = file_parents.values()[0]
2076
versionedfile = self.repository.weave_store.get_weave(file_id,
2077
self.repository.get_transaction())
2078
versionedfile.clone_text(self._new_revision_id,
2079
previous_ie.revision, file_parents.keys())
2080
return text_sha1, text_size
2082
new_lines = get_content_byte_lines()
2083
# TODO: Rather than invoking sha_strings here, _add_text_to_weave
2084
# should return the SHA1 and size
2085
self._add_text_to_weave(file_id, new_lines, file_parents.keys())
2086
return osutils.sha_strings(new_lines), \
2087
sum(map(len, new_lines))
2089
def modified_link(self, file_id, file_parents, link_target):
2090
"""Record the presence of a symbolic link.
2092
:param file_id: The file_id of the link to record.
2093
:param file_parents: The per-file parent revision ids.
2094
:param link_target: Target location of this link.
2096
self._add_text_to_weave(file_id, [], file_parents.keys())
2098
def _add_text_to_weave(self, file_id, new_lines, parents):
2099
versionedfile = self.repository.weave_store.get_weave_or_empty(
2100
file_id, self.repository.get_transaction())
2101
versionedfile.add_lines(self._new_revision_id, parents, new_lines)
2102
versionedfile.clear_cache()
2105
class _CommitBuilder(CommitBuilder):
2106
"""Temporary class so old CommitBuilders are detected properly
2108
Note: CommitBuilder works whether or not root entry is recorded.
2111
record_root_entry = True
2114
class RootCommitBuilder(CommitBuilder):
2115
"""This commitbuilder actually records the root id"""
2117
record_root_entry = True
2119
def record_entry_contents(self, ie, parent_invs, path, tree):
2120
"""Record the content of ie from tree into the commit if needed.
2122
Side effect: sets ie.revision when unchanged
2124
:param ie: An inventory entry present in the commit.
2125
:param parent_invs: The inventories of the parent revisions of the
2127
:param path: The path the entry is at in the tree.
2128
:param tree: The tree which contains this entry and should be used to
2131
assert self.new_inventory.root is not None or ie.parent_id is None
2132
self.new_inventory.add(ie)
2134
# ie.revision is always None if the InventoryEntry is considered
2135
# for committing. ie.snapshot will record the correct revision
2136
# which may be the sole parent if it is untouched.
2137
if ie.revision is not None:
2140
previous_entries = ie.find_previous_heads(
2142
self.repository.weave_store,
2143
self.repository.get_transaction())
2144
# we are creating a new revision for ie in the history store
2146
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2158
def _unescaper(match, _map=_unescape_map):
2159
code = match.group(1)
2163
if not code.startswith('#'):
2165
return unichr(int(code[1:])).encode('utf8')
2171
def _unescape_xml(data):
2172
"""Unescape predefined XML entities in a string of data."""
2174
if _unescape_re is None:
2175
_unescape_re = re.compile('\&([^;]*);')
2176
return _unescape_re.sub(_unescaper, data)