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(), """
37
revision as _mod_revision,
42
from bzrlib.revisiontree import RevisionTree
43
from bzrlib.store.versioned import VersionedFileStore
44
from bzrlib.store.text import TextStore
45
from bzrlib.testament import Testament
49
from bzrlib.decorators import needs_read_lock, needs_write_lock
50
from bzrlib.inter import InterObject
51
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
52
from bzrlib.symbol_versioning import (
56
from bzrlib.trace import mutter, note, warning
59
# Old formats display a warning, but only once
60
_deprecation_warning_done = False
63
######################################################################
66
class Repository(object):
67
"""Repository holding history for one or more branches.
69
The repository holds and retrieves historical information including
70
revisions and file history. It's normally accessed only by the Branch,
71
which views a particular line of development through that history.
73
The Repository builds on top of Stores and a Transport, which respectively
74
describe the disk data format and the way of accessing the (possibly
78
_file_ids_altered_regex = lazy_regex.lazy_compile(
79
r'file_id="(?P<file_id>[^"]+)"'
80
r'.*revision="(?P<revision_id>[^"]+)"'
84
def add_inventory(self, revid, inv, parents):
85
"""Add the inventory inv to the repository as revid.
87
:param parents: The revision ids of the parents that revid
88
is known to have and are in the repository already.
90
returns the sha1 of the serialized inventory.
92
_mod_revision.check_not_reserved_id(revid)
93
assert inv.revision_id is None or inv.revision_id == revid, \
94
"Mismatch between inventory revision" \
95
" id and insertion revid (%r, %r)" % (inv.revision_id, revid)
96
assert inv.root is not None
97
inv_text = self.serialise_inventory(inv)
98
inv_sha1 = osutils.sha_string(inv_text)
99
inv_vf = self.control_weaves.get_weave('inventory',
100
self.get_transaction())
101
self._inventory_add_lines(inv_vf, revid, parents, osutils.split_lines(inv_text))
104
def _inventory_add_lines(self, inv_vf, revid, parents, lines):
106
for parent in parents:
108
final_parents.append(parent)
110
inv_vf.add_lines(revid, final_parents, lines)
113
def add_revision(self, rev_id, rev, inv=None, config=None):
114
"""Add rev to the revision store as rev_id.
116
:param rev_id: the revision id to use.
117
:param rev: The revision object.
118
:param inv: The inventory for the revision. if None, it will be looked
119
up in the inventory storer
120
:param config: If None no digital signature will be created.
121
If supplied its signature_needed method will be used
122
to determine if a signature should be made.
124
_mod_revision.check_not_reserved_id(rev_id)
125
if config is not None and config.signature_needed():
127
inv = self.get_inventory(rev_id)
128
plaintext = Testament(rev, inv).as_short_text()
129
self.store_revision_signature(
130
gpg.GPGStrategy(config), plaintext, rev_id)
131
if not rev_id in self.get_inventory_weave():
133
raise errors.WeaveRevisionNotPresent(rev_id,
134
self.get_inventory_weave())
136
# yes, this is not suitable for adding with ghosts.
137
self.add_inventory(rev_id, inv, rev.parent_ids)
138
self._revision_store.add_revision(rev, self.get_transaction())
141
def _all_possible_ids(self):
142
"""Return all the possible revisions that we could find."""
143
return self.get_inventory_weave().versions()
145
def all_revision_ids(self):
146
"""Returns a list of all the revision ids in the repository.
148
This is deprecated because code should generally work on the graph
149
reachable from a particular revision, and ignore any other revisions
150
that might be present. There is no direct replacement method.
152
return self._all_revision_ids()
155
def _all_revision_ids(self):
156
"""Returns a list of all the revision ids in the repository.
158
These are in as much topological order as the underlying store can
159
present: for weaves ghosts may lead to a lack of correctness until
160
the reweave updates the parents list.
162
if self._revision_store.text_store.listable():
163
return self._revision_store.all_revision_ids(self.get_transaction())
164
result = self._all_possible_ids()
165
return self._eliminate_revisions_not_present(result)
167
def break_lock(self):
168
"""Break a lock if one is present from another instance.
170
Uses the ui factory to ask for confirmation if the lock may be from
173
self.control_files.break_lock()
176
def _eliminate_revisions_not_present(self, revision_ids):
177
"""Check every revision id in revision_ids to see if we have it.
179
Returns a set of the present revisions.
182
for id in revision_ids:
183
if self.has_revision(id):
188
def create(a_bzrdir):
189
"""Construct the current default format repository in a_bzrdir."""
190
return RepositoryFormat.get_default_format().initialize(a_bzrdir)
192
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
193
"""instantiate a Repository.
195
:param _format: The format of the repository on disk.
196
:param a_bzrdir: The BzrDir of the repository.
198
In the future we will have a single api for all stores for
199
getting file texts, inventories and revisions, then
200
this construct will accept instances of those things.
202
super(Repository, self).__init__()
203
self._format = _format
204
# the following are part of the public API for Repository:
205
self.bzrdir = a_bzrdir
206
self.control_files = control_files
207
self._revision_store = _revision_store
208
self.text_store = text_store
209
# backwards compatibility
210
self.weave_store = text_store
211
# not right yet - should be more semantically clear ?
213
self.control_store = control_store
214
self.control_weaves = control_store
215
# TODO: make sure to construct the right store classes, etc, depending
216
# on whether escaping is required.
217
self._warn_if_deprecated()
220
return '%s(%r)' % (self.__class__.__name__,
221
self.bzrdir.transport.base)
224
return self.control_files.is_locked()
226
def lock_write(self):
227
self.control_files.lock_write()
230
self.control_files.lock_read()
232
def get_physical_lock_status(self):
233
return self.control_files.get_physical_lock_status()
236
def gather_stats(self, revid=None, committers=None):
237
"""Gather statistics from a revision id.
239
:param revid: The revision id to gather statistics from, if None, then
240
no revision specific statistics are gathered.
241
:param committers: Optional parameter controlling whether to grab
242
a count of committers from the revision specific statistics.
243
:return: A dictionary of statistics. Currently this contains:
244
committers: The number of committers if requested.
245
firstrev: A tuple with timestamp, timezone for the penultimate left
246
most ancestor of revid, if revid is not the NULL_REVISION.
247
latestrev: A tuple with timestamp, timezone for revid, if revid is
248
not the NULL_REVISION.
249
revisions: The total revision count in the repository.
250
size: An estimate disk size of the repository in bytes.
253
if revid and committers:
254
result['committers'] = 0
255
if revid and revid != _mod_revision.NULL_REVISION:
257
all_committers = set()
258
revisions = self.get_ancestry(revid)
259
# pop the leading None
261
first_revision = None
263
# ignore the revisions in the middle - just grab first and last
264
revisions = revisions[0], revisions[-1]
265
for revision in self.get_revisions(revisions):
266
if not first_revision:
267
first_revision = revision
269
all_committers.add(revision.committer)
270
last_revision = revision
272
result['committers'] = len(all_committers)
273
result['firstrev'] = (first_revision.timestamp,
274
first_revision.timezone)
275
result['latestrev'] = (last_revision.timestamp,
276
last_revision.timezone)
278
# now gather global repository information
279
if self.bzrdir.root_transport.listable():
280
c, t = self._revision_store.total_size(self.get_transaction())
281
result['revisions'] = c
286
def missing_revision_ids(self, other, revision_id=None):
287
"""Return the revision ids that other has that this does not.
289
These are returned in topological order.
291
revision_id: only return revision ids included by revision_id.
293
return InterRepository.get(other, self).missing_revision_ids(revision_id)
297
"""Open the repository rooted at base.
299
For instance, if the repository is at URL/.bzr/repository,
300
Repository.open(URL) -> a Repository instance.
302
control = bzrdir.BzrDir.open(base)
303
return control.open_repository()
305
def copy_content_into(self, destination, revision_id=None, basis=None):
306
"""Make a complete copy of the content in self into destination.
308
This is a destructive operation! Do not use it on existing
311
return InterRepository.get(self, destination).copy_content(revision_id, basis)
313
def fetch(self, source, revision_id=None, pb=None):
314
"""Fetch the content required to construct revision_id from source.
316
If revision_id is None all content is copied.
318
return InterRepository.get(source, self).fetch(revision_id=revision_id,
321
def get_commit_builder(self, branch, parents, config, timestamp=None,
322
timezone=None, committer=None, revprops=None,
324
"""Obtain a CommitBuilder for this repository.
326
:param branch: Branch to commit to.
327
:param parents: Revision ids of the parents of the new revision.
328
:param config: Configuration to use.
329
:param timestamp: Optional timestamp recorded for commit.
330
:param timezone: Optional timezone for timestamp.
331
:param committer: Optional committer to set for commit.
332
:param revprops: Optional dictionary of revision properties.
333
:param revision_id: Optional revision id.
335
return _CommitBuilder(self, parents, config, timestamp, timezone,
336
committer, revprops, revision_id)
339
self.control_files.unlock()
342
def clone(self, a_bzrdir, revision_id=None, basis=None):
343
"""Clone this repository into a_bzrdir using the current format.
345
Currently no check is made that the format of this repository and
346
the bzrdir format are compatible. FIXME RBC 20060201.
348
:return: The newly created destination repository.
350
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
351
# use target default format.
352
dest_repo = a_bzrdir.create_repository()
354
# Most control formats need the repository to be specifically
355
# created, but on some old all-in-one formats it's not needed
357
dest_repo = self._format.initialize(a_bzrdir, shared=self.is_shared())
358
except errors.UninitializableFormat:
359
dest_repo = a_bzrdir.open_repository()
360
self.copy_content_into(dest_repo, revision_id, basis)
364
def has_revision(self, revision_id):
365
"""True if this repository has a copy of the revision."""
366
return self._revision_store.has_revision_id(revision_id,
367
self.get_transaction())
370
def get_revision_reconcile(self, revision_id):
371
"""'reconcile' helper routine that allows access to a revision always.
373
This variant of get_revision does not cross check the weave graph
374
against the revision one as get_revision does: but it should only
375
be used by reconcile, or reconcile-alike commands that are correcting
376
or testing the revision graph.
378
if not revision_id or not isinstance(revision_id, basestring):
379
raise errors.InvalidRevisionId(revision_id=revision_id,
381
return self._revision_store.get_revisions([revision_id],
382
self.get_transaction())[0]
384
def get_revisions(self, revision_ids):
385
return self._revision_store.get_revisions(revision_ids,
386
self.get_transaction())
389
def get_revision_xml(self, revision_id):
390
rev = self.get_revision(revision_id)
392
# the current serializer..
393
self._revision_store._serializer.write_revision(rev, rev_tmp)
395
return rev_tmp.getvalue()
398
def get_revision(self, revision_id):
399
"""Return the Revision object for a named revision"""
400
r = self.get_revision_reconcile(revision_id)
401
# weave corruption can lead to absent revision markers that should be
403
# the following test is reasonably cheap (it needs a single weave read)
404
# and the weave is cached in read transactions. In write transactions
405
# it is not cached but typically we only read a small number of
406
# revisions. For knits when they are introduced we will probably want
407
# to ensure that caching write transactions are in use.
408
inv = self.get_inventory_weave()
409
self._check_revision_parents(r, inv)
413
def get_deltas_for_revisions(self, revisions):
414
"""Produce a generator of revision deltas.
416
Note that the input is a sequence of REVISIONS, not revision_ids.
417
Trees will be held in memory until the generator exits.
418
Each delta is relative to the revision's lefthand predecessor.
420
required_trees = set()
421
for revision in revisions:
422
required_trees.add(revision.revision_id)
423
required_trees.update(revision.parent_ids[:1])
424
trees = dict((t.get_revision_id(), t) for
425
t in self.revision_trees(required_trees))
426
for revision in revisions:
427
if not revision.parent_ids:
428
old_tree = self.revision_tree(None)
430
old_tree = trees[revision.parent_ids[0]]
431
yield trees[revision.revision_id].changes_from(old_tree)
434
def get_revision_delta(self, revision_id):
435
"""Return the delta for one revision.
437
The delta is relative to the left-hand predecessor of the
440
r = self.get_revision(revision_id)
441
return list(self.get_deltas_for_revisions([r]))[0]
443
def _check_revision_parents(self, revision, inventory):
444
"""Private to Repository and Fetch.
446
This checks the parentage of revision in an inventory weave for
447
consistency and is only applicable to inventory-weave-for-ancestry
448
using repository formats & fetchers.
450
weave_parents = inventory.get_parents(revision.revision_id)
451
weave_names = inventory.versions()
452
for parent_id in revision.parent_ids:
453
if parent_id in weave_names:
454
# this parent must not be a ghost.
455
if not parent_id in weave_parents:
457
raise errors.CorruptRepository(self)
460
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
461
signature = gpg_strategy.sign(plaintext)
462
self._revision_store.add_revision_signature_text(revision_id,
464
self.get_transaction())
466
def fileids_altered_by_revision_ids(self, revision_ids):
467
"""Find the file ids and versions affected by revisions.
469
:param revisions: an iterable containing revision ids.
470
:return: a dictionary mapping altered file-ids to an iterable of
471
revision_ids. Each altered file-ids has the exact revision_ids that
472
altered it listed explicitly.
474
assert self._serializer.support_altered_by_hack, \
475
("fileids_altered_by_revision_ids only supported for branches "
476
"which store inventory as unnested xml, not on %r" % self)
477
selected_revision_ids = set(revision_ids)
478
w = self.get_inventory_weave()
481
# this code needs to read every new line in every inventory for the
482
# inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
483
# not present in one of those inventories is unnecessary but not
484
# harmful because we are filtering by the revision id marker in the
485
# inventory lines : we only select file ids altered in one of those
486
# revisions. We don't need to see all lines in the inventory because
487
# only those added in an inventory in rev X can contain a revision=X
489
unescape_revid_cache = {}
490
unescape_fileid_cache = {}
492
# jam 20061218 In a big fetch, this handles hundreds of thousands
493
# of lines, so it has had a lot of inlining and optimizing done.
494
# Sorry that it is a little bit messy.
495
# Move several functions to be local variables, since this is a long
497
search = self._file_ids_altered_regex.search
498
unescape = _unescape_xml
499
setdefault = result.setdefault
500
pb = ui.ui_factory.nested_progress_bar()
502
for line in w.iter_lines_added_or_present_in_versions(
503
selected_revision_ids, pb=pb):
507
# One call to match.group() returning multiple items is quite a
508
# bit faster than 2 calls to match.group() each returning 1
509
file_id, revision_id = match.group('file_id', 'revision_id')
511
# Inlining the cache lookups helps a lot when you make 170,000
512
# lines and 350k ids, versus 8.4 unique ids.
513
# Using a cache helps in 2 ways:
514
# 1) Avoids unnecessary decoding calls
515
# 2) Re-uses cached strings, which helps in future set and
517
# (2) is enough that removing encoding entirely along with
518
# the cache (so we are using plain strings) results in no
519
# performance improvement.
521
revision_id = unescape_revid_cache[revision_id]
523
unescaped = unescape(revision_id)
524
unescape_revid_cache[revision_id] = unescaped
525
revision_id = unescaped
527
if revision_id in selected_revision_ids:
529
file_id = unescape_fileid_cache[file_id]
531
unescaped = unescape(file_id)
532
unescape_fileid_cache[file_id] = unescaped
534
setdefault(file_id, set()).add(revision_id)
540
def get_inventory_weave(self):
541
return self.control_weaves.get_weave('inventory',
542
self.get_transaction())
545
def get_inventory(self, revision_id):
546
"""Get Inventory object by hash."""
547
return self.deserialise_inventory(
548
revision_id, self.get_inventory_xml(revision_id))
550
def deserialise_inventory(self, revision_id, xml):
551
"""Transform the xml into an inventory object.
553
:param revision_id: The expected revision id of the inventory.
554
:param xml: A serialised inventory.
556
result = self._serializer.read_inventory_from_string(xml)
557
result.root.revision = revision_id
560
def serialise_inventory(self, inv):
561
return self._serializer.write_inventory_to_string(inv)
564
def get_inventory_xml(self, revision_id):
565
"""Get inventory XML as a file object."""
567
assert isinstance(revision_id, basestring), type(revision_id)
568
iw = self.get_inventory_weave()
569
return iw.get_text(revision_id)
571
raise errors.HistoryMissing(self, 'inventory', revision_id)
574
def get_inventory_sha1(self, revision_id):
575
"""Return the sha1 hash of the inventory entry
577
return self.get_revision(revision_id).inventory_sha1
580
def get_revision_graph(self, revision_id=None):
581
"""Return a dictionary containing the revision graph.
583
:param revision_id: The revision_id to get a graph from. If None, then
584
the entire revision graph is returned. This is a deprecated mode of
585
operation and will be removed in the future.
586
:return: a dictionary of revision_id->revision_parents_list.
588
# special case NULL_REVISION
589
if revision_id == _mod_revision.NULL_REVISION:
591
a_weave = self.get_inventory_weave()
592
all_revisions = self._eliminate_revisions_not_present(
594
entire_graph = dict([(node, a_weave.get_parents(node)) for
595
node in all_revisions])
596
if revision_id is None:
598
elif revision_id not in entire_graph:
599
raise errors.NoSuchRevision(self, revision_id)
601
# add what can be reached from revision_id
603
pending = set([revision_id])
604
while len(pending) > 0:
606
result[node] = entire_graph[node]
607
for revision_id in result[node]:
608
if revision_id not in result:
609
pending.add(revision_id)
613
def get_revision_graph_with_ghosts(self, revision_ids=None):
614
"""Return a graph of the revisions with ghosts marked as applicable.
616
:param revision_ids: an iterable of revisions to graph or None for all.
617
:return: a Graph object with the graph reachable from revision_ids.
619
result = graph.Graph()
621
pending = set(self.all_revision_ids())
624
pending = set(revision_ids)
625
# special case NULL_REVISION
626
if _mod_revision.NULL_REVISION in pending:
627
pending.remove(_mod_revision.NULL_REVISION)
628
required = set(pending)
631
revision_id = pending.pop()
633
rev = self.get_revision(revision_id)
634
except errors.NoSuchRevision:
635
if revision_id in required:
638
result.add_ghost(revision_id)
640
for parent_id in rev.parent_ids:
641
# is this queued or done ?
642
if (parent_id not in pending and
643
parent_id not in done):
645
pending.add(parent_id)
646
result.add_node(revision_id, rev.parent_ids)
647
done.add(revision_id)
651
def get_revision_inventory(self, revision_id):
652
"""Return inventory of a past revision."""
653
# TODO: Unify this with get_inventory()
654
# bzr 0.0.6 and later imposes the constraint that the inventory_id
655
# must be the same as its revision, so this is trivial.
656
if revision_id is None:
657
# This does not make sense: if there is no revision,
658
# then it is the current tree inventory surely ?!
659
# and thus get_root_id() is something that looks at the last
660
# commit on the branch, and the get_root_id is an inventory check.
661
raise NotImplementedError
662
# return Inventory(self.get_root_id())
664
return self.get_inventory(revision_id)
668
"""Return True if this repository is flagged as a shared repository."""
669
raise NotImplementedError(self.is_shared)
672
def reconcile(self, other=None, thorough=False):
673
"""Reconcile this repository."""
674
from bzrlib.reconcile import RepoReconciler
675
reconciler = RepoReconciler(self, thorough=thorough)
676
reconciler.reconcile()
680
def revision_tree(self, revision_id):
681
"""Return Tree for a revision on this branch.
683
`revision_id` may be None for the empty tree revision.
685
# TODO: refactor this to use an existing revision object
686
# so we don't need to read it in twice.
687
if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
688
return RevisionTree(self, Inventory(root_id=None),
689
_mod_revision.NULL_REVISION)
691
inv = self.get_revision_inventory(revision_id)
692
return RevisionTree(self, inv, revision_id)
695
def revision_trees(self, revision_ids):
696
"""Return Tree for a revision on this branch.
698
`revision_id` may not be None or 'null:'"""
699
assert None not in revision_ids
700
assert _mod_revision.NULL_REVISION not in revision_ids
701
texts = self.get_inventory_weave().get_texts(revision_ids)
702
for text, revision_id in zip(texts, revision_ids):
703
inv = self.deserialise_inventory(revision_id, text)
704
yield RevisionTree(self, inv, revision_id)
707
def get_ancestry(self, revision_id):
708
"""Return a list of revision-ids integrated by a revision.
710
The first element of the list is always None, indicating the origin
711
revision. This might change when we have history horizons, or
712
perhaps we should have a new API.
714
This is topologically sorted.
716
if revision_id is None:
718
if not self.has_revision(revision_id):
719
raise errors.NoSuchRevision(self, revision_id)
720
w = self.get_inventory_weave()
721
candidates = w.get_ancestry(revision_id)
722
return [None] + candidates # self._eliminate_revisions_not_present(candidates)
725
def print_file(self, file, revision_id):
726
"""Print `file` to stdout.
728
FIXME RBC 20060125 as John Meinel points out this is a bad api
729
- it writes to stdout, it assumes that that is valid etc. Fix
730
by creating a new more flexible convenience function.
732
tree = self.revision_tree(revision_id)
733
# use inventory as it was in that revision
734
file_id = tree.inventory.path2id(file)
736
# TODO: jam 20060427 Write a test for this code path
737
# it had a bug in it, and was raising the wrong
739
raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
740
tree.print_file(file_id)
742
def get_transaction(self):
743
return self.control_files.get_transaction()
745
def revision_parents(self, revid):
746
return self.get_inventory_weave().parent_names(revid)
749
def set_make_working_trees(self, new_value):
750
"""Set the policy flag for making working trees when creating branches.
752
This only applies to branches that use this repository.
754
The default is 'True'.
755
:param new_value: True to restore the default, False to disable making
758
raise NotImplementedError(self.set_make_working_trees)
760
def make_working_trees(self):
761
"""Returns the policy for making working trees on new branches."""
762
raise NotImplementedError(self.make_working_trees)
765
def sign_revision(self, revision_id, gpg_strategy):
766
plaintext = Testament.from_revision(self, revision_id).as_short_text()
767
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
770
def has_signature_for_revision_id(self, revision_id):
771
"""Query for a revision signature for revision_id in the repository."""
772
return self._revision_store.has_signature(revision_id,
773
self.get_transaction())
776
def get_signature_text(self, revision_id):
777
"""Return the text for a signature."""
778
return self._revision_store.get_signature_text(revision_id,
779
self.get_transaction())
782
def check(self, revision_ids):
783
"""Check consistency of all history of given revision_ids.
785
Different repository implementations should override _check().
787
:param revision_ids: A non-empty list of revision_ids whose ancestry
788
will be checked. Typically the last revision_id of a branch.
791
raise ValueError("revision_ids must be non-empty in %s.check"
793
return self._check(revision_ids)
795
def _check(self, revision_ids):
796
result = check.Check(self)
800
def _warn_if_deprecated(self):
801
global _deprecation_warning_done
802
if _deprecation_warning_done:
804
_deprecation_warning_done = True
805
warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
806
% (self._format, self.bzrdir.transport.base))
808
def supports_rich_root(self):
809
return self._format.rich_root_data
811
def _check_ascii_revisionid(self, revision_id, method):
812
"""Private helper for ascii-only repositories."""
813
# weave repositories refuse to store revisionids that are non-ascii.
814
if revision_id is not None:
815
# weaves require ascii revision ids.
816
if isinstance(revision_id, unicode):
818
revision_id.encode('ascii')
819
except UnicodeEncodeError:
820
raise errors.NonAsciiRevisionId(method, self)
824
# remove these delegates a while after bzr 0.15
825
def __make_delegated(name, from_module):
826
def _deprecated_repository_forwarder():
827
symbol_versioning.warn('%s moved to %s in bzr 0.15'
828
% (name, from_module),
831
m = __import__(from_module, globals(), locals(), [name])
833
return getattr(m, name)
834
except AttributeError:
835
raise AttributeError('module %s has no name %s'
837
globals()[name] = _deprecated_repository_forwarder
840
'AllInOneRepository',
841
'WeaveMetaDirRepository',
842
'PreSplitOutRepositoryFormat',
848
__make_delegated(_name, 'bzrlib.repofmt.weaverepo')
853
'RepositoryFormatKnit',
854
'RepositoryFormatKnit1',
855
'RepositoryFormatKnit2',
857
__make_delegated(_name, 'bzrlib.repofmt.knitrepo')
860
def install_revision(repository, rev, revision_tree):
861
"""Install all revision data into a repository."""
864
for p_id in rev.parent_ids:
865
if repository.has_revision(p_id):
866
present_parents.append(p_id)
867
parent_trees[p_id] = repository.revision_tree(p_id)
869
parent_trees[p_id] = repository.revision_tree(None)
871
inv = revision_tree.inventory
872
entries = inv.iter_entries()
873
# backwards compatability hack: skip the root id.
874
if not repository.supports_rich_root():
875
path, root = entries.next()
876
if root.revision != rev.revision_id:
877
raise errors.IncompatibleRevision(repr(repository))
878
# Add the texts that are not already present
879
for path, ie in entries:
880
w = repository.weave_store.get_weave_or_empty(ie.file_id,
881
repository.get_transaction())
882
if ie.revision not in w:
884
# FIXME: TODO: The following loop *may* be overlapping/duplicate
885
# with InventoryEntry.find_previous_heads(). if it is, then there
886
# is a latent bug here where the parents may have ancestors of each
888
for revision, tree in parent_trees.iteritems():
889
if ie.file_id not in tree:
891
parent_id = tree.inventory[ie.file_id].revision
892
if parent_id in text_parents:
894
text_parents.append(parent_id)
896
vfile = repository.weave_store.get_weave_or_empty(ie.file_id,
897
repository.get_transaction())
898
lines = revision_tree.get_file(ie.file_id).readlines()
899
vfile.add_lines(rev.revision_id, text_parents, lines)
901
# install the inventory
902
repository.add_inventory(rev.revision_id, inv, present_parents)
903
except errors.RevisionAlreadyPresent:
905
repository.add_revision(rev.revision_id, rev, inv)
908
class MetaDirRepository(Repository):
909
"""Repositories in the new meta-dir layout."""
911
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
912
super(MetaDirRepository, self).__init__(_format,
918
dir_mode = self.control_files._dir_mode
919
file_mode = self.control_files._file_mode
923
"""Return True if this repository is flagged as a shared repository."""
924
return self.control_files._transport.has('shared-storage')
927
def set_make_working_trees(self, new_value):
928
"""Set the policy flag for making working trees when creating branches.
930
This only applies to branches that use this repository.
932
The default is 'True'.
933
:param new_value: True to restore the default, False to disable making
938
self.control_files._transport.delete('no-working-trees')
939
except errors.NoSuchFile:
942
self.control_files.put_utf8('no-working-trees', '')
944
def make_working_trees(self):
945
"""Returns the policy for making working trees on new branches."""
946
return not self.control_files._transport.has('no-working-trees')
949
class RepositoryFormatRegistry(registry.Registry):
950
"""Registry of RepositoryFormats.
953
def get(self, format_string):
954
r = registry.Registry.get(self, format_string)
960
format_registry = RepositoryFormatRegistry()
961
"""Registry of formats, indexed by their identifying format string.
963
This can contain either format instances themselves, or classes/factories that
964
can be called to obtain one.
968
#####################################################################
971
class RepositoryFormat(object):
972
"""A repository format.
974
Formats provide three things:
975
* An initialization routine to construct repository data on disk.
976
* a format string which is used when the BzrDir supports versioned
978
* an open routine which returns a Repository instance.
980
Formats are placed in an dict by their format string for reference
981
during opening. These should be subclasses of RepositoryFormat
984
Once a format is deprecated, just deprecate the initialize and open
985
methods on the format class. Do not deprecate the object, as the
986
object will be created every system load.
988
Common instance attributes:
989
_matchingbzrdir - the bzrdir format that the repository format was
990
originally written to work with. This can be used if manually
991
constructing a bzrdir and repository, or more commonly for test suite
996
return "<%s>" % self.__class__.__name__
998
def __eq__(self, other):
999
# format objects are generally stateless
1000
return isinstance(other, self.__class__)
1003
def find_format(klass, a_bzrdir):
1004
"""Return the format for the repository object in a_bzrdir.
1006
This is used by bzr native formats that have a "format" file in
1007
the repository. Other methods may be used by different types of
1011
transport = a_bzrdir.get_repository_transport(None)
1012
format_string = transport.get("format").read()
1013
return format_registry.get(format_string)
1014
except errors.NoSuchFile:
1015
raise errors.NoRepositoryPresent(a_bzrdir)
1017
raise errors.UnknownFormatError(format=format_string)
1020
def register_format(klass, format):
1021
format_registry.register(format.get_format_string(), format)
1024
def unregister_format(klass, format):
1025
format_registry.remove(format.get_format_string())
1028
def get_default_format(klass):
1029
"""Return the current default format."""
1030
from bzrlib import bzrdir
1031
return bzrdir.format_registry.make_bzrdir('default').repository_format
1033
def _get_control_store(self, repo_transport, control_files):
1034
"""Return the control store for this repository."""
1035
raise NotImplementedError(self._get_control_store)
1037
def get_format_string(self):
1038
"""Return the ASCII format string that identifies this format.
1040
Note that in pre format ?? repositories the format string is
1041
not permitted nor written to disk.
1043
raise NotImplementedError(self.get_format_string)
1045
def get_format_description(self):
1046
"""Return the short description for this format."""
1047
raise NotImplementedError(self.get_format_description)
1049
def _get_revision_store(self, repo_transport, control_files):
1050
"""Return the revision store object for this a_bzrdir."""
1051
raise NotImplementedError(self._get_revision_store)
1053
def _get_text_rev_store(self,
1060
"""Common logic for getting a revision store for a repository.
1062
see self._get_revision_store for the subclass-overridable method to
1063
get the store for a repository.
1065
from bzrlib.store.revision.text import TextRevisionStore
1066
dir_mode = control_files._dir_mode
1067
file_mode = control_files._file_mode
1068
text_store = TextStore(transport.clone(name),
1070
compressed=compressed,
1072
file_mode=file_mode)
1073
_revision_store = TextRevisionStore(text_store, serializer)
1074
return _revision_store
1076
# TODO: this shouldn't be in the base class, it's specific to things that
1077
# use weaves or knits -- mbp 20070207
1078
def _get_versioned_file_store(self,
1083
versionedfile_class=None,
1084
versionedfile_kwargs={},
1086
if versionedfile_class is None:
1087
versionedfile_class = self._versionedfile_class
1088
weave_transport = control_files._transport.clone(name)
1089
dir_mode = control_files._dir_mode
1090
file_mode = control_files._file_mode
1091
return VersionedFileStore(weave_transport, prefixed=prefixed,
1093
file_mode=file_mode,
1094
versionedfile_class=versionedfile_class,
1095
versionedfile_kwargs=versionedfile_kwargs,
1098
def initialize(self, a_bzrdir, shared=False):
1099
"""Initialize a repository of this format in a_bzrdir.
1101
:param a_bzrdir: The bzrdir to put the new repository in it.
1102
:param shared: The repository should be initialized as a sharable one.
1104
This may raise UninitializableFormat if shared repository are not
1105
compatible the a_bzrdir.
1108
def is_supported(self):
1109
"""Is this format supported?
1111
Supported formats must be initializable and openable.
1112
Unsupported formats may not support initialization or committing or
1113
some other features depending on the reason for not being supported.
1117
def check_conversion_target(self, target_format):
1118
raise NotImplementedError(self.check_conversion_target)
1120
def open(self, a_bzrdir, _found=False):
1121
"""Return an instance of this format for the bzrdir a_bzrdir.
1123
_found is a private parameter, do not use it.
1125
raise NotImplementedError(self.open)
1128
class MetaDirRepositoryFormat(RepositoryFormat):
1129
"""Common base class for the new repositories using the metadir layout."""
1131
rich_root_data = False
1132
_matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1135
super(MetaDirRepositoryFormat, self).__init__()
1137
def _create_control_files(self, a_bzrdir):
1138
"""Create the required files and the initial control_files object."""
1139
# FIXME: RBC 20060125 don't peek under the covers
1140
# NB: no need to escape relative paths that are url safe.
1141
repository_transport = a_bzrdir.get_repository_transport(self)
1142
control_files = lockable_files.LockableFiles(repository_transport,
1143
'lock', lockdir.LockDir)
1144
control_files.create_lock()
1145
return control_files
1147
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1148
"""Upload the initial blank content."""
1149
control_files = self._create_control_files(a_bzrdir)
1150
control_files.lock_write()
1152
control_files._transport.mkdir_multi(dirs,
1153
mode=control_files._dir_mode)
1154
for file, content in files:
1155
control_files.put(file, content)
1156
for file, content in utf8_files:
1157
control_files.put_utf8(file, content)
1159
control_files.put_utf8('shared-storage', '')
1161
control_files.unlock()
1164
# formats which have no format string are not discoverable
1165
# and not independently creatable, so are not registered. They're
1166
# all in bzrlib.repofmt.weaverepo now. When an instance of one of these is
1167
# needed, it's constructed directly by the BzrDir. Non-native formats where
1168
# the repository is not separately opened are similar.
1170
format_registry.register_lazy(
1171
'Bazaar-NG Repository format 7',
1172
'bzrlib.repofmt.weaverepo',
1175
# KEEP in sync with bzrdir.format_registry default, which controls the overall
1176
# default control directory format
1178
format_registry.register_lazy(
1179
'Bazaar-NG Knit Repository Format 1',
1180
'bzrlib.repofmt.knitrepo',
1181
'RepositoryFormatKnit1',
1183
format_registry.default_key = 'Bazaar-NG Knit Repository Format 1'
1185
format_registry.register_lazy(
1186
'Bazaar Knit Repository Format 2\n',
1187
'bzrlib.repofmt.knitrepo',
1188
'RepositoryFormatKnit2',
1192
class InterRepository(InterObject):
1193
"""This class represents operations taking place between two repositories.
1195
Its instances have methods like copy_content and fetch, and contain
1196
references to the source and target repositories these operations can be
1199
Often we will provide convenience methods on 'repository' which carry out
1200
operations with another repository - they will always forward to
1201
InterRepository.get(other).method_name(parameters).
1205
"""The available optimised InterRepository types."""
1207
def copy_content(self, revision_id=None, basis=None):
1208
raise NotImplementedError(self.copy_content)
1210
def fetch(self, revision_id=None, pb=None):
1211
"""Fetch the content required to construct revision_id.
1213
The content is copied from self.source to self.target.
1215
:param revision_id: if None all content is copied, if NULL_REVISION no
1217
:param pb: optional progress bar to use for progress reports. If not
1218
provided a default one will be created.
1220
Returns the copied revision count and the failed revisions in a tuple:
1223
raise NotImplementedError(self.fetch)
1226
def missing_revision_ids(self, revision_id=None):
1227
"""Return the revision ids that source has that target does not.
1229
These are returned in topological order.
1231
:param revision_id: only return revision ids included by this
1234
# generic, possibly worst case, slow code path.
1235
target_ids = set(self.target.all_revision_ids())
1236
if revision_id is not None:
1237
source_ids = self.source.get_ancestry(revision_id)
1238
assert source_ids[0] is None
1241
source_ids = self.source.all_revision_ids()
1242
result_set = set(source_ids).difference(target_ids)
1243
# this may look like a no-op: its not. It preserves the ordering
1244
# other_ids had while only returning the members from other_ids
1245
# that we've decided we need.
1246
return [rev_id for rev_id in source_ids if rev_id in result_set]
1249
class InterSameDataRepository(InterRepository):
1250
"""Code for converting between repositories that represent the same data.
1252
Data format and model must match for this to work.
1256
def _get_repo_format_to_test(self):
1257
"""Repository format for testing with."""
1258
return RepositoryFormat.get_default_format()
1261
def is_compatible(source, target):
1262
if not isinstance(source, Repository):
1264
if not isinstance(target, Repository):
1266
if source._format.rich_root_data == target._format.rich_root_data:
1272
def copy_content(self, revision_id=None, basis=None):
1273
"""Make a complete copy of the content in self into destination.
1275
This is a destructive operation! Do not use it on existing
1278
:param revision_id: Only copy the content needed to construct
1279
revision_id and its parents.
1280
:param basis: Copy the needed data preferentially from basis.
1283
self.target.set_make_working_trees(self.source.make_working_trees())
1284
except NotImplementedError:
1286
# grab the basis available data
1287
if basis is not None:
1288
self.target.fetch(basis, revision_id=revision_id)
1289
# but don't bother fetching if we have the needed data now.
1290
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1291
self.target.has_revision(revision_id)):
1293
self.target.fetch(self.source, revision_id=revision_id)
1296
def fetch(self, revision_id=None, pb=None):
1297
"""See InterRepository.fetch()."""
1298
from bzrlib.fetch import GenericRepoFetcher
1299
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1300
self.source, self.source._format, self.target,
1301
self.target._format)
1302
f = GenericRepoFetcher(to_repository=self.target,
1303
from_repository=self.source,
1304
last_revision=revision_id,
1306
return f.count_copied, f.failed_revisions
1309
class InterWeaveRepo(InterSameDataRepository):
1310
"""Optimised code paths between Weave based repositories."""
1313
def _get_repo_format_to_test(self):
1314
from bzrlib.repofmt import weaverepo
1315
return weaverepo.RepositoryFormat7()
1318
def is_compatible(source, target):
1319
"""Be compatible with known Weave formats.
1321
We don't test for the stores being of specific types because that
1322
could lead to confusing results, and there is no need to be
1325
from bzrlib.repofmt.weaverepo import (
1331
return (isinstance(source._format, (RepositoryFormat5,
1333
RepositoryFormat7)) and
1334
isinstance(target._format, (RepositoryFormat5,
1336
RepositoryFormat7)))
1337
except AttributeError:
1341
def copy_content(self, revision_id=None, basis=None):
1342
"""See InterRepository.copy_content()."""
1343
# weave specific optimised path:
1344
if basis is not None:
1345
# copy the basis in, then fetch remaining data.
1346
basis.copy_content_into(self.target, revision_id)
1347
# the basis copy_content_into could miss-set this.
1349
self.target.set_make_working_trees(self.source.make_working_trees())
1350
except NotImplementedError:
1352
self.target.fetch(self.source, revision_id=revision_id)
1355
self.target.set_make_working_trees(self.source.make_working_trees())
1356
except NotImplementedError:
1358
# FIXME do not peek!
1359
if self.source.control_files._transport.listable():
1360
pb = ui.ui_factory.nested_progress_bar()
1362
self.target.weave_store.copy_all_ids(
1363
self.source.weave_store,
1365
from_transaction=self.source.get_transaction(),
1366
to_transaction=self.target.get_transaction())
1367
pb.update('copying inventory', 0, 1)
1368
self.target.control_weaves.copy_multi(
1369
self.source.control_weaves, ['inventory'],
1370
from_transaction=self.source.get_transaction(),
1371
to_transaction=self.target.get_transaction())
1372
self.target._revision_store.text_store.copy_all_ids(
1373
self.source._revision_store.text_store,
1378
self.target.fetch(self.source, revision_id=revision_id)
1381
def fetch(self, revision_id=None, pb=None):
1382
"""See InterRepository.fetch()."""
1383
from bzrlib.fetch import GenericRepoFetcher
1384
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1385
self.source, self.source._format, self.target, self.target._format)
1386
f = GenericRepoFetcher(to_repository=self.target,
1387
from_repository=self.source,
1388
last_revision=revision_id,
1390
return f.count_copied, f.failed_revisions
1393
def missing_revision_ids(self, revision_id=None):
1394
"""See InterRepository.missing_revision_ids()."""
1395
# we want all revisions to satisfy revision_id in source.
1396
# but we don't want to stat every file here and there.
1397
# we want then, all revisions other needs to satisfy revision_id
1398
# checked, but not those that we have locally.
1399
# so the first thing is to get a subset of the revisions to
1400
# satisfy revision_id in source, and then eliminate those that
1401
# we do already have.
1402
# this is slow on high latency connection to self, but as as this
1403
# disk format scales terribly for push anyway due to rewriting
1404
# inventory.weave, this is considered acceptable.
1406
if revision_id is not None:
1407
source_ids = self.source.get_ancestry(revision_id)
1408
assert source_ids[0] is None
1411
source_ids = self.source._all_possible_ids()
1412
source_ids_set = set(source_ids)
1413
# source_ids is the worst possible case we may need to pull.
1414
# now we want to filter source_ids against what we actually
1415
# have in target, but don't try to check for existence where we know
1416
# we do not have a revision as that would be pointless.
1417
target_ids = set(self.target._all_possible_ids())
1418
possibly_present_revisions = target_ids.intersection(source_ids_set)
1419
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1420
required_revisions = source_ids_set.difference(actually_present_revisions)
1421
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1422
if revision_id is not None:
1423
# we used get_ancestry to determine source_ids then we are assured all
1424
# revisions referenced are present as they are installed in topological order.
1425
# and the tip revision was validated by get_ancestry.
1426
return required_topo_revisions
1428
# if we just grabbed the possibly available ids, then
1429
# we only have an estimate of whats available and need to validate
1430
# that against the revision records.
1431
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1434
class InterKnitRepo(InterSameDataRepository):
1435
"""Optimised code paths between Knit based repositories."""
1438
def _get_repo_format_to_test(self):
1439
from bzrlib.repofmt import knitrepo
1440
return knitrepo.RepositoryFormatKnit1()
1443
def is_compatible(source, target):
1444
"""Be compatible with known Knit formats.
1446
We don't test for the stores being of specific types because that
1447
could lead to confusing results, and there is no need to be
1450
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1
1452
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1453
isinstance(target._format, (RepositoryFormatKnit1)))
1454
except AttributeError:
1458
def fetch(self, revision_id=None, pb=None):
1459
"""See InterRepository.fetch()."""
1460
from bzrlib.fetch import KnitRepoFetcher
1461
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1462
self.source, self.source._format, self.target, self.target._format)
1463
f = KnitRepoFetcher(to_repository=self.target,
1464
from_repository=self.source,
1465
last_revision=revision_id,
1467
return f.count_copied, f.failed_revisions
1470
def missing_revision_ids(self, revision_id=None):
1471
"""See InterRepository.missing_revision_ids()."""
1472
if revision_id is not None:
1473
source_ids = self.source.get_ancestry(revision_id)
1474
assert source_ids[0] is None
1477
source_ids = self.source._all_possible_ids()
1478
source_ids_set = set(source_ids)
1479
# source_ids is the worst possible case we may need to pull.
1480
# now we want to filter source_ids against what we actually
1481
# have in target, but don't try to check for existence where we know
1482
# we do not have a revision as that would be pointless.
1483
target_ids = set(self.target._all_possible_ids())
1484
possibly_present_revisions = target_ids.intersection(source_ids_set)
1485
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1486
required_revisions = source_ids_set.difference(actually_present_revisions)
1487
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1488
if revision_id is not None:
1489
# we used get_ancestry to determine source_ids then we are assured all
1490
# revisions referenced are present as they are installed in topological order.
1491
# and the tip revision was validated by get_ancestry.
1492
return required_topo_revisions
1494
# if we just grabbed the possibly available ids, then
1495
# we only have an estimate of whats available and need to validate
1496
# that against the revision records.
1497
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1500
class InterModel1and2(InterRepository):
1503
def _get_repo_format_to_test(self):
1507
def is_compatible(source, target):
1508
if not isinstance(source, Repository):
1510
if not isinstance(target, Repository):
1512
if not source._format.rich_root_data and target._format.rich_root_data:
1518
def fetch(self, revision_id=None, pb=None):
1519
"""See InterRepository.fetch()."""
1520
from bzrlib.fetch import Model1toKnit2Fetcher
1521
f = Model1toKnit2Fetcher(to_repository=self.target,
1522
from_repository=self.source,
1523
last_revision=revision_id,
1525
return f.count_copied, f.failed_revisions
1528
def copy_content(self, revision_id=None, basis=None):
1529
"""Make a complete copy of the content in self into destination.
1531
This is a destructive operation! Do not use it on existing
1534
:param revision_id: Only copy the content needed to construct
1535
revision_id and its parents.
1536
:param basis: Copy the needed data preferentially from basis.
1539
self.target.set_make_working_trees(self.source.make_working_trees())
1540
except NotImplementedError:
1542
# grab the basis available data
1543
if basis is not None:
1544
self.target.fetch(basis, revision_id=revision_id)
1545
# but don't bother fetching if we have the needed data now.
1546
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1547
self.target.has_revision(revision_id)):
1549
self.target.fetch(self.source, revision_id=revision_id)
1552
class InterKnit1and2(InterKnitRepo):
1555
def _get_repo_format_to_test(self):
1559
def is_compatible(source, target):
1560
"""Be compatible with Knit1 source and Knit2 target"""
1561
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit2
1563
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1, \
1564
RepositoryFormatKnit2
1565
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1566
isinstance(target._format, (RepositoryFormatKnit2)))
1567
except AttributeError:
1571
def fetch(self, revision_id=None, pb=None):
1572
"""See InterRepository.fetch()."""
1573
from bzrlib.fetch import Knit1to2Fetcher
1574
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1575
self.source, self.source._format, self.target,
1576
self.target._format)
1577
f = Knit1to2Fetcher(to_repository=self.target,
1578
from_repository=self.source,
1579
last_revision=revision_id,
1581
return f.count_copied, f.failed_revisions
1584
InterRepository.register_optimiser(InterSameDataRepository)
1585
InterRepository.register_optimiser(InterWeaveRepo)
1586
InterRepository.register_optimiser(InterKnitRepo)
1587
InterRepository.register_optimiser(InterModel1and2)
1588
InterRepository.register_optimiser(InterKnit1and2)
1591
class RepositoryTestProviderAdapter(object):
1592
"""A tool to generate a suite testing multiple repository formats at once.
1594
This is done by copying the test once for each transport and injecting
1595
the transport_server, transport_readonly_server, and bzrdir_format and
1596
repository_format classes into each copy. Each copy is also given a new id()
1597
to make it easy to identify.
1600
def __init__(self, transport_server, transport_readonly_server, formats):
1601
self._transport_server = transport_server
1602
self._transport_readonly_server = transport_readonly_server
1603
self._formats = formats
1605
def adapt(self, test):
1606
result = unittest.TestSuite()
1607
for repository_format, bzrdir_format in self._formats:
1608
from copy import deepcopy
1609
new_test = deepcopy(test)
1610
new_test.transport_server = self._transport_server
1611
new_test.transport_readonly_server = self._transport_readonly_server
1612
new_test.bzrdir_format = bzrdir_format
1613
new_test.repository_format = repository_format
1614
def make_new_test_id():
1615
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1616
return lambda: new_id
1617
new_test.id = make_new_test_id()
1618
result.addTest(new_test)
1622
class InterRepositoryTestProviderAdapter(object):
1623
"""A tool to generate a suite testing multiple inter repository formats.
1625
This is done by copying the test once for each interrepo provider and injecting
1626
the transport_server, transport_readonly_server, repository_format and
1627
repository_to_format classes into each copy.
1628
Each copy is also given a new id() to make it easy to identify.
1631
def __init__(self, transport_server, transport_readonly_server, formats):
1632
self._transport_server = transport_server
1633
self._transport_readonly_server = transport_readonly_server
1634
self._formats = formats
1636
def adapt(self, test):
1637
result = unittest.TestSuite()
1638
for interrepo_class, repository_format, repository_format_to in self._formats:
1639
from copy import deepcopy
1640
new_test = deepcopy(test)
1641
new_test.transport_server = self._transport_server
1642
new_test.transport_readonly_server = self._transport_readonly_server
1643
new_test.interrepo_class = interrepo_class
1644
new_test.repository_format = repository_format
1645
new_test.repository_format_to = repository_format_to
1646
def make_new_test_id():
1647
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1648
return lambda: new_id
1649
new_test.id = make_new_test_id()
1650
result.addTest(new_test)
1654
def default_test_list():
1655
"""Generate the default list of interrepo permutations to test."""
1656
from bzrlib.repofmt import knitrepo, weaverepo
1658
# test the default InterRepository between format 6 and the current
1660
# XXX: robertc 20060220 reinstate this when there are two supported
1661
# formats which do not have an optimal code path between them.
1662
#result.append((InterRepository,
1663
# RepositoryFormat6(),
1664
# RepositoryFormatKnit1()))
1665
for optimiser_class in InterRepository._optimisers:
1666
format_to_test = optimiser_class._get_repo_format_to_test()
1667
if format_to_test is not None:
1668
result.append((optimiser_class,
1669
format_to_test, format_to_test))
1670
# if there are specific combinations we want to use, we can add them
1672
result.append((InterModel1and2,
1673
weaverepo.RepositoryFormat5(),
1674
knitrepo.RepositoryFormatKnit2()))
1675
result.append((InterKnit1and2,
1676
knitrepo.RepositoryFormatKnit1(),
1677
knitrepo.RepositoryFormatKnit2()))
1681
class CopyConverter(object):
1682
"""A repository conversion tool which just performs a copy of the content.
1684
This is slow but quite reliable.
1687
def __init__(self, target_format):
1688
"""Create a CopyConverter.
1690
:param target_format: The format the resulting repository should be.
1692
self.target_format = target_format
1694
def convert(self, repo, pb):
1695
"""Perform the conversion of to_convert, giving feedback via pb.
1697
:param to_convert: The disk object to convert.
1698
:param pb: a progress bar to use for progress information.
1703
# this is only useful with metadir layouts - separated repo content.
1704
# trigger an assertion if not such
1705
repo._format.get_format_string()
1706
self.repo_dir = repo.bzrdir
1707
self.step('Moving repository to repository.backup')
1708
self.repo_dir.transport.move('repository', 'repository.backup')
1709
backup_transport = self.repo_dir.transport.clone('repository.backup')
1710
repo._format.check_conversion_target(self.target_format)
1711
self.source_repo = repo._format.open(self.repo_dir,
1713
_override_transport=backup_transport)
1714
self.step('Creating new repository')
1715
converted = self.target_format.initialize(self.repo_dir,
1716
self.source_repo.is_shared())
1717
converted.lock_write()
1719
self.step('Copying content into repository.')
1720
self.source_repo.copy_content_into(converted)
1723
self.step('Deleting old repository content.')
1724
self.repo_dir.transport.delete_tree('repository.backup')
1725
self.pb.note('repository converted')
1727
def step(self, message):
1728
"""Update the pb by a step."""
1730
self.pb.update(message, self.count, self.total)
1733
class CommitBuilder(object):
1734
"""Provides an interface to build up a commit.
1736
This allows describing a tree to be committed without needing to
1737
know the internals of the format of the repository.
1740
record_root_entry = False
1741
def __init__(self, repository, parents, config, timestamp=None,
1742
timezone=None, committer=None, revprops=None,
1744
"""Initiate a CommitBuilder.
1746
:param repository: Repository to commit to.
1747
:param parents: Revision ids of the parents of the new revision.
1748
:param config: Configuration to use.
1749
:param timestamp: Optional timestamp recorded for commit.
1750
:param timezone: Optional timezone for timestamp.
1751
:param committer: Optional committer to set for commit.
1752
:param revprops: Optional dictionary of revision properties.
1753
:param revision_id: Optional revision id.
1755
self._config = config
1757
if committer is None:
1758
self._committer = self._config.username()
1760
assert isinstance(committer, basestring), type(committer)
1761
self._committer = committer
1763
self.new_inventory = Inventory(None)
1764
self._new_revision_id = revision_id
1765
self.parents = parents
1766
self.repository = repository
1769
if revprops is not None:
1770
self._revprops.update(revprops)
1772
if timestamp is None:
1773
timestamp = time.time()
1774
# Restrict resolution to 1ms
1775
self._timestamp = round(timestamp, 3)
1777
if timezone is None:
1778
self._timezone = osutils.local_time_offset()
1780
self._timezone = int(timezone)
1782
self._generate_revision_if_needed()
1784
def commit(self, message):
1785
"""Make the actual commit.
1787
:return: The revision id of the recorded revision.
1789
rev = _mod_revision.Revision(
1790
timestamp=self._timestamp,
1791
timezone=self._timezone,
1792
committer=self._committer,
1794
inventory_sha1=self.inv_sha1,
1795
revision_id=self._new_revision_id,
1796
properties=self._revprops)
1797
rev.parent_ids = self.parents
1798
self.repository.add_revision(self._new_revision_id, rev,
1799
self.new_inventory, self._config)
1800
return self._new_revision_id
1802
def revision_tree(self):
1803
"""Return the tree that was just committed.
1805
After calling commit() this can be called to get a RevisionTree
1806
representing the newly committed tree. This is preferred to
1807
calling Repository.revision_tree() because that may require
1808
deserializing the inventory, while we already have a copy in
1811
return RevisionTree(self.repository, self.new_inventory,
1812
self._new_revision_id)
1814
def finish_inventory(self):
1815
"""Tell the builder that the inventory is finished."""
1816
if self.new_inventory.root is None:
1817
symbol_versioning.warn('Root entry should be supplied to'
1818
' record_entry_contents, as of bzr 0.10.',
1819
DeprecationWarning, stacklevel=2)
1820
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
1821
self.new_inventory.revision_id = self._new_revision_id
1822
self.inv_sha1 = self.repository.add_inventory(
1823
self._new_revision_id,
1828
def _gen_revision_id(self):
1829
"""Return new revision-id."""
1830
return generate_ids.gen_revision_id(self._config.username(),
1833
def _generate_revision_if_needed(self):
1834
"""Create a revision id if None was supplied.
1836
If the repository can not support user-specified revision ids
1837
they should override this function and raise CannotSetRevisionId
1838
if _new_revision_id is not None.
1840
:raises: CannotSetRevisionId
1842
if self._new_revision_id is None:
1843
self._new_revision_id = self._gen_revision_id()
1845
def record_entry_contents(self, ie, parent_invs, path, tree):
1846
"""Record the content of ie from tree into the commit if needed.
1848
Side effect: sets ie.revision when unchanged
1850
:param ie: An inventory entry present in the commit.
1851
:param parent_invs: The inventories of the parent revisions of the
1853
:param path: The path the entry is at in the tree.
1854
:param tree: The tree which contains this entry and should be used to
1857
if self.new_inventory.root is None and ie.parent_id is not None:
1858
symbol_versioning.warn('Root entry should be supplied to'
1859
' record_entry_contents, as of bzr 0.10.',
1860
DeprecationWarning, stacklevel=2)
1861
self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
1863
self.new_inventory.add(ie)
1865
# ie.revision is always None if the InventoryEntry is considered
1866
# for committing. ie.snapshot will record the correct revision
1867
# which may be the sole parent if it is untouched.
1868
if ie.revision is not None:
1871
# In this revision format, root entries have no knit or weave
1872
if ie is self.new_inventory.root:
1873
# When serializing out to disk and back in
1874
# root.revision is always _new_revision_id
1875
ie.revision = self._new_revision_id
1877
previous_entries = ie.find_previous_heads(
1879
self.repository.weave_store,
1880
self.repository.get_transaction())
1881
# we are creating a new revision for ie in the history store
1883
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
1885
def modified_directory(self, file_id, file_parents):
1886
"""Record the presence of a symbolic link.
1888
:param file_id: The file_id of the link to record.
1889
:param file_parents: The per-file parent revision ids.
1891
self._add_text_to_weave(file_id, [], file_parents.keys())
1893
def modified_file_text(self, file_id, file_parents,
1894
get_content_byte_lines, text_sha1=None,
1896
"""Record the text of file file_id
1898
:param file_id: The file_id of the file to record the text of.
1899
:param file_parents: The per-file parent revision ids.
1900
:param get_content_byte_lines: A callable which will return the byte
1902
:param text_sha1: Optional SHA1 of the file contents.
1903
:param text_size: Optional size of the file contents.
1905
# mutter('storing text of file {%s} in revision {%s} into %r',
1906
# file_id, self._new_revision_id, self.repository.weave_store)
1907
# special case to avoid diffing on renames or
1909
if (len(file_parents) == 1
1910
and text_sha1 == file_parents.values()[0].text_sha1
1911
and text_size == file_parents.values()[0].text_size):
1912
previous_ie = file_parents.values()[0]
1913
versionedfile = self.repository.weave_store.get_weave(file_id,
1914
self.repository.get_transaction())
1915
versionedfile.clone_text(self._new_revision_id,
1916
previous_ie.revision, file_parents.keys())
1917
return text_sha1, text_size
1919
new_lines = get_content_byte_lines()
1920
# TODO: Rather than invoking sha_strings here, _add_text_to_weave
1921
# should return the SHA1 and size
1922
self._add_text_to_weave(file_id, new_lines, file_parents.keys())
1923
return osutils.sha_strings(new_lines), \
1924
sum(map(len, new_lines))
1926
def modified_link(self, file_id, file_parents, link_target):
1927
"""Record the presence of a symbolic link.
1929
:param file_id: The file_id of the link to record.
1930
:param file_parents: The per-file parent revision ids.
1931
:param link_target: Target location of this link.
1933
self._add_text_to_weave(file_id, [], file_parents.keys())
1935
def _add_text_to_weave(self, file_id, new_lines, parents):
1936
versionedfile = self.repository.weave_store.get_weave_or_empty(
1937
file_id, self.repository.get_transaction())
1938
versionedfile.add_lines(self._new_revision_id, parents, new_lines)
1939
versionedfile.clear_cache()
1942
class _CommitBuilder(CommitBuilder):
1943
"""Temporary class so old CommitBuilders are detected properly
1945
Note: CommitBuilder works whether or not root entry is recorded.
1948
record_root_entry = True
1951
class RootCommitBuilder(CommitBuilder):
1952
"""This commitbuilder actually records the root id"""
1954
record_root_entry = True
1956
def record_entry_contents(self, ie, parent_invs, path, tree):
1957
"""Record the content of ie from tree into the commit if needed.
1959
Side effect: sets ie.revision when unchanged
1961
:param ie: An inventory entry present in the commit.
1962
:param parent_invs: The inventories of the parent revisions of the
1964
:param path: The path the entry is at in the tree.
1965
:param tree: The tree which contains this entry and should be used to
1968
assert self.new_inventory.root is not None or ie.parent_id is None
1969
self.new_inventory.add(ie)
1971
# ie.revision is always None if the InventoryEntry is considered
1972
# for committing. ie.snapshot will record the correct revision
1973
# which may be the sole parent if it is untouched.
1974
if ie.revision is not None:
1977
previous_entries = ie.find_previous_heads(
1979
self.repository.weave_store,
1980
self.repository.get_transaction())
1981
# we are creating a new revision for ie in the history store
1983
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
1995
def _unescaper(match, _map=_unescape_map):
1996
return _map[match.group(1)]
2002
def _unescape_xml(data):
2003
"""Unescape predefined XML entities in a string of data."""
2005
if _unescape_re is None:
2006
_unescape_re = re.compile('\&([^;]*);')
2007
return _unescape_re.sub(_unescaper, data)