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(), """
21
from binascii import hexlify
22
from copy import deepcopy
41
revision as _mod_revision,
50
from bzrlib.osutils import (
55
from bzrlib.revisiontree import RevisionTree
56
from bzrlib.store.versioned import VersionedFileStore
57
from bzrlib.store.text import TextStore
58
from bzrlib.testament import Testament
61
from bzrlib.decorators import needs_read_lock, needs_write_lock
62
from bzrlib.inter import InterObject
63
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
64
from bzrlib.symbol_versioning import (
68
from bzrlib.trace import mutter, note, warning
71
# Old formats display a warning, but only once
72
_deprecation_warning_done = False
75
class Repository(object):
76
"""Repository holding history for one or more branches.
78
The repository holds and retrieves historical information including
79
revisions and file history. It's normally accessed only by the Branch,
80
which views a particular line of development through that history.
82
The Repository builds on top of Stores and a Transport, which respectively
83
describe the disk data format and the way of accessing the (possibly
87
_file_ids_altered_regex = lazy_regex.lazy_compile(
88
r'file_id="(?P<file_id>[^"]+)"'
89
r'.*revision="(?P<revision_id>[^"]+)"'
93
def add_inventory(self, revid, inv, parents):
94
"""Add the inventory inv to the repository as revid.
96
:param parents: The revision ids of the parents that revid
97
is known to have and are in the repository already.
99
returns the sha1 of the serialized inventory.
101
_mod_revision.check_not_reserved_id(revid)
102
assert inv.revision_id is None or inv.revision_id == revid, \
103
"Mismatch between inventory revision" \
104
" id and insertion revid (%r, %r)" % (inv.revision_id, revid)
105
assert inv.root is not None
106
inv_text = self.serialise_inventory(inv)
107
inv_sha1 = osutils.sha_string(inv_text)
108
inv_vf = self.control_weaves.get_weave('inventory',
109
self.get_transaction())
110
self._inventory_add_lines(inv_vf, revid, parents, osutils.split_lines(inv_text))
113
def _inventory_add_lines(self, inv_vf, revid, parents, lines):
115
for parent in parents:
117
final_parents.append(parent)
119
inv_vf.add_lines(revid, final_parents, lines)
122
def add_revision(self, rev_id, rev, inv=None, config=None):
123
"""Add rev to the revision store as rev_id.
125
:param rev_id: the revision id to use.
126
:param rev: The revision object.
127
:param inv: The inventory for the revision. if None, it will be looked
128
up in the inventory storer
129
:param config: If None no digital signature will be created.
130
If supplied its signature_needed method will be used
131
to determine if a signature should be made.
133
_mod_revision.check_not_reserved_id(rev_id)
134
if config is not None and config.signature_needed():
136
inv = self.get_inventory(rev_id)
137
plaintext = Testament(rev, inv).as_short_text()
138
self.store_revision_signature(
139
gpg.GPGStrategy(config), plaintext, rev_id)
140
if not rev_id in self.get_inventory_weave():
142
raise errors.WeaveRevisionNotPresent(rev_id,
143
self.get_inventory_weave())
145
# yes, this is not suitable for adding with ghosts.
146
self.add_inventory(rev_id, inv, rev.parent_ids)
147
self._revision_store.add_revision(rev, self.get_transaction())
150
def _all_possible_ids(self):
151
"""Return all the possible revisions that we could find."""
152
return self.get_inventory_weave().versions()
154
def all_revision_ids(self):
155
"""Returns a list of all the revision ids in the repository.
157
This is deprecated because code should generally work on the graph
158
reachable from a particular revision, and ignore any other revisions
159
that might be present. There is no direct replacement method.
161
return self._all_revision_ids()
164
def _all_revision_ids(self):
165
"""Returns a list of all the revision ids in the repository.
167
These are in as much topological order as the underlying store can
168
present: for weaves ghosts may lead to a lack of correctness until
169
the reweave updates the parents list.
171
if self._revision_store.text_store.listable():
172
return self._revision_store.all_revision_ids(self.get_transaction())
173
result = self._all_possible_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()
227
self._serializer = xml5.serializer_v5
230
return '%s(%r)' % (self.__class__.__name__,
231
self.bzrdir.transport.base)
234
return self.control_files.is_locked()
236
def lock_write(self):
237
self.control_files.lock_write()
240
self.control_files.lock_read()
242
def get_physical_lock_status(self):
243
return self.control_files.get_physical_lock_status()
246
def missing_revision_ids(self, other, revision_id=None):
247
"""Return the revision ids that other has that this does not.
249
These are returned in topological order.
251
revision_id: only return revision ids included by revision_id.
253
return InterRepository.get(other, self).missing_revision_ids(revision_id)
257
"""Open the repository rooted at base.
259
For instance, if the repository is at URL/.bzr/repository,
260
Repository.open(URL) -> a Repository instance.
262
control = bzrdir.BzrDir.open(base)
263
return control.open_repository()
265
def copy_content_into(self, destination, revision_id=None, basis=None):
266
"""Make a complete copy of the content in self into destination.
268
This is a destructive operation! Do not use it on existing
271
return InterRepository.get(self, destination).copy_content(revision_id, basis)
273
def fetch(self, source, revision_id=None, pb=None):
274
"""Fetch the content required to construct revision_id from source.
276
If revision_id is None all content is copied.
278
return InterRepository.get(source, self).fetch(revision_id=revision_id,
281
def get_commit_builder(self, branch, parents, config, timestamp=None,
282
timezone=None, committer=None, revprops=None,
284
"""Obtain a CommitBuilder for this repository.
286
:param branch: Branch to commit to.
287
:param parents: Revision ids of the parents of the new revision.
288
:param config: Configuration to use.
289
:param timestamp: Optional timestamp recorded for commit.
290
:param timezone: Optional timezone for timestamp.
291
:param committer: Optional committer to set for commit.
292
:param revprops: Optional dictionary of revision properties.
293
:param revision_id: Optional revision id.
295
return _CommitBuilder(self, parents, config, timestamp, timezone,
296
committer, revprops, revision_id)
299
self.control_files.unlock()
302
def clone(self, a_bzrdir, revision_id=None, basis=None):
303
"""Clone this repository into a_bzrdir using the current format.
305
Currently no check is made that the format of this repository and
306
the bzrdir format are compatible. FIXME RBC 20060201.
308
:return: The newly created destination repository.
310
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
311
# use target default format.
312
dest_repo = a_bzrdir.create_repository()
314
# Most control formats need the repository to be specifically
315
# created, but on some old all-in-one formats it's not needed
317
dest_repo = self._format.initialize(a_bzrdir, shared=self.is_shared())
318
except errors.UninitializableFormat:
319
dest_repo = a_bzrdir.open_repository()
320
self.copy_content_into(dest_repo, revision_id, basis)
324
def has_revision(self, revision_id):
325
"""True if this repository has a copy of the revision."""
326
return self._revision_store.has_revision_id(revision_id,
327
self.get_transaction())
330
def get_revision_reconcile(self, revision_id):
331
"""'reconcile' helper routine that allows access to a revision always.
333
This variant of get_revision does not cross check the weave graph
334
against the revision one as get_revision does: but it should only
335
be used by reconcile, or reconcile-alike commands that are correcting
336
or testing the revision graph.
338
if not revision_id or not isinstance(revision_id, basestring):
339
raise errors.InvalidRevisionId(revision_id=revision_id,
341
return self._revision_store.get_revisions([revision_id],
342
self.get_transaction())[0]
344
def get_revisions(self, revision_ids):
345
return self._revision_store.get_revisions(revision_ids,
346
self.get_transaction())
349
def get_revision_xml(self, revision_id):
350
rev = self.get_revision(revision_id)
352
# the current serializer..
353
self._revision_store._serializer.write_revision(rev, rev_tmp)
355
return rev_tmp.getvalue()
358
def get_revision(self, revision_id):
359
"""Return the Revision object for a named revision"""
360
r = self.get_revision_reconcile(revision_id)
361
# weave corruption can lead to absent revision markers that should be
363
# the following test is reasonably cheap (it needs a single weave read)
364
# and the weave is cached in read transactions. In write transactions
365
# it is not cached but typically we only read a small number of
366
# revisions. For knits when they are introduced we will probably want
367
# to ensure that caching write transactions are in use.
368
inv = self.get_inventory_weave()
369
self._check_revision_parents(r, inv)
373
def get_deltas_for_revisions(self, revisions):
374
"""Produce a generator of revision deltas.
376
Note that the input is a sequence of REVISIONS, not revision_ids.
377
Trees will be held in memory until the generator exits.
378
Each delta is relative to the revision's lefthand predecessor.
380
required_trees = set()
381
for revision in revisions:
382
required_trees.add(revision.revision_id)
383
required_trees.update(revision.parent_ids[:1])
384
trees = dict((t.get_revision_id(), t) for
385
t in self.revision_trees(required_trees))
386
for revision in revisions:
387
if not revision.parent_ids:
388
old_tree = self.revision_tree(None)
390
old_tree = trees[revision.parent_ids[0]]
391
yield trees[revision.revision_id].changes_from(old_tree)
394
def get_revision_delta(self, revision_id):
395
"""Return the delta for one revision.
397
The delta is relative to the left-hand predecessor of the
400
r = self.get_revision(revision_id)
401
return list(self.get_deltas_for_revisions([r]))[0]
403
def _check_revision_parents(self, revision, inventory):
404
"""Private to Repository and Fetch.
406
This checks the parentage of revision in an inventory weave for
407
consistency and is only applicable to inventory-weave-for-ancestry
408
using repository formats & fetchers.
410
weave_parents = inventory.get_parents(revision.revision_id)
411
weave_names = inventory.versions()
412
for parent_id in revision.parent_ids:
413
if parent_id in weave_names:
414
# this parent must not be a ghost.
415
if not parent_id in weave_parents:
417
raise errors.CorruptRepository(self)
420
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
421
signature = gpg_strategy.sign(plaintext)
422
self._revision_store.add_revision_signature_text(revision_id,
424
self.get_transaction())
426
def fileids_altered_by_revision_ids(self, revision_ids):
427
"""Find the file ids and versions affected by revisions.
429
:param revisions: an iterable containing revision ids.
430
:return: a dictionary mapping altered file-ids to an iterable of
431
revision_ids. Each altered file-ids has the exact revision_ids that
432
altered it listed explicitly.
434
assert self._serializer.support_altered_by_hack, \
435
("fileids_altered_by_revision_ids only supported for branches "
436
"which store inventory as unnested xml, not on %r" % self)
437
selected_revision_ids = set(revision_ids)
438
w = self.get_inventory_weave()
441
# this code needs to read every new line in every inventory for the
442
# inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
443
# not present in one of those inventories is unnecessary but not
444
# harmful because we are filtering by the revision id marker in the
445
# inventory lines : we only select file ids altered in one of those
446
# revisions. We don't need to see all lines in the inventory because
447
# only those added in an inventory in rev X can contain a revision=X
449
unescape_revid_cache = {}
450
unescape_fileid_cache = {}
452
# jam 20061218 In a big fetch, this handles hundreds of thousands
453
# of lines, so it has had a lot of inlining and optimizing done.
454
# Sorry that it is a little bit messy.
455
# Move several functions to be local variables, since this is a long
457
search = self._file_ids_altered_regex.search
458
unescape = _unescape_xml
459
setdefault = result.setdefault
460
pb = ui.ui_factory.nested_progress_bar()
462
for line in w.iter_lines_added_or_present_in_versions(
463
selected_revision_ids, pb=pb):
467
# One call to match.group() returning multiple items is quite a
468
# bit faster than 2 calls to match.group() each returning 1
469
file_id, revision_id = match.group('file_id', 'revision_id')
471
# Inlining the cache lookups helps a lot when you make 170,000
472
# lines and 350k ids, versus 8.4 unique ids.
473
# Using a cache helps in 2 ways:
474
# 1) Avoids unnecessary decoding calls
475
# 2) Re-uses cached strings, which helps in future set and
477
# (2) is enough that removing encoding entirely along with
478
# the cache (so we are using plain strings) results in no
479
# performance improvement.
481
revision_id = unescape_revid_cache[revision_id]
483
unescaped = unescape(revision_id)
484
unescape_revid_cache[revision_id] = unescaped
485
revision_id = unescaped
487
if revision_id in selected_revision_ids:
489
file_id = unescape_fileid_cache[file_id]
491
unescaped = unescape(file_id)
492
unescape_fileid_cache[file_id] = unescaped
494
setdefault(file_id, set()).add(revision_id)
500
def get_inventory_weave(self):
501
return self.control_weaves.get_weave('inventory',
502
self.get_transaction())
505
def get_inventory(self, revision_id):
506
"""Get Inventory object by hash."""
507
return self.deserialise_inventory(
508
revision_id, self.get_inventory_xml(revision_id))
510
def deserialise_inventory(self, revision_id, xml):
511
"""Transform the xml into an inventory object.
513
:param revision_id: The expected revision id of the inventory.
514
:param xml: A serialised inventory.
516
result = self._serializer.read_inventory_from_string(xml)
517
result.root.revision = revision_id
520
def serialise_inventory(self, inv):
521
return self._serializer.write_inventory_to_string(inv)
524
def get_inventory_xml(self, revision_id):
525
"""Get inventory XML as a file object."""
527
assert isinstance(revision_id, basestring), type(revision_id)
528
iw = self.get_inventory_weave()
529
return iw.get_text(revision_id)
531
raise errors.HistoryMissing(self, 'inventory', revision_id)
534
def get_inventory_sha1(self, revision_id):
535
"""Return the sha1 hash of the inventory entry
537
return self.get_revision(revision_id).inventory_sha1
540
def get_revision_graph(self, revision_id=None):
541
"""Return a dictionary containing the revision graph.
543
:param revision_id: The revision_id to get a graph from. If None, then
544
the entire revision graph is returned. This is a deprecated mode of
545
operation and will be removed in the future.
546
:return: a dictionary of revision_id->revision_parents_list.
548
# special case NULL_REVISION
549
if revision_id == _mod_revision.NULL_REVISION:
551
a_weave = self.get_inventory_weave()
552
all_revisions = self._eliminate_revisions_not_present(
554
entire_graph = dict([(node, a_weave.get_parents(node)) for
555
node in all_revisions])
556
if revision_id is None:
558
elif revision_id not in entire_graph:
559
raise errors.NoSuchRevision(self, revision_id)
561
# add what can be reached from revision_id
563
pending = set([revision_id])
564
while len(pending) > 0:
566
result[node] = entire_graph[node]
567
for revision_id in result[node]:
568
if revision_id not in result:
569
pending.add(revision_id)
573
def get_revision_graph_with_ghosts(self, revision_ids=None):
574
"""Return a graph of the revisions with ghosts marked as applicable.
576
:param revision_ids: an iterable of revisions to graph or None for all.
577
:return: a Graph object with the graph reachable from revision_ids.
579
result = graph.Graph()
581
pending = set(self.all_revision_ids())
584
pending = set(revision_ids)
585
# special case NULL_REVISION
586
if _mod_revision.NULL_REVISION in pending:
587
pending.remove(_mod_revision.NULL_REVISION)
588
required = set(pending)
591
revision_id = pending.pop()
593
rev = self.get_revision(revision_id)
594
except errors.NoSuchRevision:
595
if revision_id in required:
598
result.add_ghost(revision_id)
600
for parent_id in rev.parent_ids:
601
# is this queued or done ?
602
if (parent_id not in pending and
603
parent_id not in done):
605
pending.add(parent_id)
606
result.add_node(revision_id, rev.parent_ids)
607
done.add(revision_id)
611
def get_revision_inventory(self, revision_id):
612
"""Return inventory of a past revision."""
613
# TODO: Unify this with get_inventory()
614
# bzr 0.0.6 and later imposes the constraint that the inventory_id
615
# must be the same as its revision, so this is trivial.
616
if revision_id is None:
617
# This does not make sense: if there is no revision,
618
# then it is the current tree inventory surely ?!
619
# and thus get_root_id() is something that looks at the last
620
# commit on the branch, and the get_root_id is an inventory check.
621
raise NotImplementedError
622
# return Inventory(self.get_root_id())
624
return self.get_inventory(revision_id)
628
"""Return True if this repository is flagged as a shared repository."""
629
raise NotImplementedError(self.is_shared)
632
def reconcile(self, other=None, thorough=False):
633
"""Reconcile this repository."""
634
from bzrlib.reconcile import RepoReconciler
635
reconciler = RepoReconciler(self, thorough=thorough)
636
reconciler.reconcile()
640
def revision_tree(self, revision_id):
641
"""Return Tree for a revision on this branch.
643
`revision_id` may be None for the empty tree revision.
645
# TODO: refactor this to use an existing revision object
646
# so we don't need to read it in twice.
647
if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
648
return RevisionTree(self, Inventory(root_id=None),
649
_mod_revision.NULL_REVISION)
651
inv = self.get_revision_inventory(revision_id)
652
return RevisionTree(self, inv, revision_id)
655
def revision_trees(self, revision_ids):
656
"""Return Tree for a revision on this branch.
658
`revision_id` may not be None or 'null:'"""
659
assert None not in revision_ids
660
assert _mod_revision.NULL_REVISION not in revision_ids
661
texts = self.get_inventory_weave().get_texts(revision_ids)
662
for text, revision_id in zip(texts, revision_ids):
663
inv = self.deserialise_inventory(revision_id, text)
664
yield RevisionTree(self, inv, revision_id)
667
def get_ancestry(self, revision_id):
668
"""Return a list of revision-ids integrated by a revision.
670
The first element of the list is always None, indicating the origin
671
revision. This might change when we have history horizons, or
672
perhaps we should have a new API.
674
This is topologically sorted.
676
if revision_id is None:
678
if not self.has_revision(revision_id):
679
raise errors.NoSuchRevision(self, revision_id)
680
w = self.get_inventory_weave()
681
candidates = w.get_ancestry(revision_id)
682
return [None] + candidates # self._eliminate_revisions_not_present(candidates)
685
def print_file(self, file, revision_id):
686
"""Print `file` to stdout.
688
FIXME RBC 20060125 as John Meinel points out this is a bad api
689
- it writes to stdout, it assumes that that is valid etc. Fix
690
by creating a new more flexible convenience function.
692
tree = self.revision_tree(revision_id)
693
# use inventory as it was in that revision
694
file_id = tree.inventory.path2id(file)
696
# TODO: jam 20060427 Write a test for this code path
697
# it had a bug in it, and was raising the wrong
699
raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
700
tree.print_file(file_id)
702
def get_transaction(self):
703
return self.control_files.get_transaction()
705
def revision_parents(self, revid):
706
return self.get_inventory_weave().parent_names(revid)
709
def set_make_working_trees(self, new_value):
710
"""Set the policy flag for making working trees when creating branches.
712
This only applies to branches that use this repository.
714
The default is 'True'.
715
:param new_value: True to restore the default, False to disable making
718
raise NotImplementedError(self.set_make_working_trees)
720
def make_working_trees(self):
721
"""Returns the policy for making working trees on new branches."""
722
raise NotImplementedError(self.make_working_trees)
725
def sign_revision(self, revision_id, gpg_strategy):
726
plaintext = Testament.from_revision(self, revision_id).as_short_text()
727
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
730
def has_signature_for_revision_id(self, revision_id):
731
"""Query for a revision signature for revision_id in the repository."""
732
return self._revision_store.has_signature(revision_id,
733
self.get_transaction())
736
def get_signature_text(self, revision_id):
737
"""Return the text for a signature."""
738
return self._revision_store.get_signature_text(revision_id,
739
self.get_transaction())
742
def check(self, revision_ids):
743
"""Check consistency of all history of given revision_ids.
745
Different repository implementations should override _check().
747
:param revision_ids: A non-empty list of revision_ids whose ancestry
748
will be checked. Typically the last revision_id of a branch.
751
raise ValueError("revision_ids must be non-empty in %s.check"
753
return self._check(revision_ids)
755
def _check(self, revision_ids):
756
result = check.Check(self)
760
def _warn_if_deprecated(self):
761
global _deprecation_warning_done
762
if _deprecation_warning_done:
764
_deprecation_warning_done = True
765
warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
766
% (self._format, self.bzrdir.transport.base))
768
def supports_rich_root(self):
769
return self._format.rich_root_data
771
def _check_ascii_revisionid(self, revision_id, method):
772
"""Private helper for ascii-only repositories."""
773
# weave repositories refuse to store revisionids that are non-ascii.
774
if revision_id is not None:
775
# weaves require ascii revision ids.
776
if isinstance(revision_id, unicode):
778
revision_id.encode('ascii')
779
except UnicodeEncodeError:
780
raise errors.NonAsciiRevisionId(method, self)
783
def install_revision(repository, rev, revision_tree):
784
"""Install all revision data into a repository."""
787
for p_id in rev.parent_ids:
788
if repository.has_revision(p_id):
789
present_parents.append(p_id)
790
parent_trees[p_id] = repository.revision_tree(p_id)
792
parent_trees[p_id] = repository.revision_tree(None)
794
inv = revision_tree.inventory
795
entries = inv.iter_entries()
796
# backwards compatability hack: skip the root id.
797
if not repository.supports_rich_root():
798
path, root = entries.next()
799
if root.revision != rev.revision_id:
800
raise errors.IncompatibleRevision(repr(repository))
801
# Add the texts that are not already present
802
for path, ie in entries:
803
w = repository.weave_store.get_weave_or_empty(ie.file_id,
804
repository.get_transaction())
805
if ie.revision not in w:
807
# FIXME: TODO: The following loop *may* be overlapping/duplicate
808
# with InventoryEntry.find_previous_heads(). if it is, then there
809
# is a latent bug here where the parents may have ancestors of each
811
for revision, tree in parent_trees.iteritems():
812
if ie.file_id not in tree:
814
parent_id = tree.inventory[ie.file_id].revision
815
if parent_id in text_parents:
817
text_parents.append(parent_id)
819
vfile = repository.weave_store.get_weave_or_empty(ie.file_id,
820
repository.get_transaction())
821
lines = revision_tree.get_file(ie.file_id).readlines()
822
vfile.add_lines(rev.revision_id, text_parents, lines)
824
# install the inventory
825
repository.add_inventory(rev.revision_id, inv, present_parents)
826
except errors.RevisionAlreadyPresent:
828
repository.add_revision(rev.revision_id, rev, inv)
831
class MetaDirRepository(Repository):
832
"""Repositories in the new meta-dir layout."""
834
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
835
super(MetaDirRepository, self).__init__(_format,
841
dir_mode = self.control_files._dir_mode
842
file_mode = self.control_files._file_mode
846
"""Return True if this repository is flagged as a shared repository."""
847
return self.control_files._transport.has('shared-storage')
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
861
self.control_files._transport.delete('no-working-trees')
862
except errors.NoSuchFile:
865
self.control_files.put_utf8('no-working-trees', '')
867
def make_working_trees(self):
868
"""Returns the policy for making working trees on new branches."""
869
return not self.control_files._transport.has('no-working-trees')
872
class KnitRepository(MetaDirRepository):
873
"""Knit format repository."""
875
def _warn_if_deprecated(self):
876
# This class isn't deprecated
879
def _inventory_add_lines(self, inv_vf, revid, parents, lines):
880
inv_vf.add_lines_with_ghosts(revid, parents, lines)
883
def _all_revision_ids(self):
884
"""See Repository.all_revision_ids()."""
885
# Knits get the revision graph from the index of the revision knit, so
886
# it's always possible even if they're on an unlistable transport.
887
return self._revision_store.all_revision_ids(self.get_transaction())
889
def fileid_involved_between_revs(self, from_revid, to_revid):
890
"""Find file_id(s) which are involved in the changes between revisions.
892
This determines the set of revisions which are involved, and then
893
finds all file ids affected by those revisions.
895
vf = self._get_revision_vf()
896
from_set = set(vf.get_ancestry(from_revid))
897
to_set = set(vf.get_ancestry(to_revid))
898
changed = to_set.difference(from_set)
899
return self._fileid_involved_by_set(changed)
901
def fileid_involved(self, last_revid=None):
902
"""Find all file_ids modified in the ancestry of last_revid.
904
:param last_revid: If None, last_revision() will be used.
907
changed = set(self.all_revision_ids())
909
changed = set(self.get_ancestry(last_revid))
912
return self._fileid_involved_by_set(changed)
915
def get_ancestry(self, revision_id):
916
"""Return a list of revision-ids integrated by a revision.
918
This is topologically sorted.
920
if revision_id is None:
922
vf = self._get_revision_vf()
924
return [None] + vf.get_ancestry(revision_id)
925
except errors.RevisionNotPresent:
926
raise errors.NoSuchRevision(self, revision_id)
929
def get_revision(self, revision_id):
930
"""Return the Revision object for a named revision"""
931
return self.get_revision_reconcile(revision_id)
934
def get_revision_graph(self, revision_id=None):
935
"""Return a dictionary containing the revision graph.
937
:param revision_id: The revision_id to get a graph from. If None, then
938
the entire revision graph is returned. This is a deprecated mode of
939
operation and will be removed in the future.
940
:return: a dictionary of revision_id->revision_parents_list.
942
# special case NULL_REVISION
943
if revision_id == _mod_revision.NULL_REVISION:
945
a_weave = self._get_revision_vf()
946
entire_graph = a_weave.get_graph()
947
if revision_id is None:
948
return a_weave.get_graph()
949
elif revision_id not in a_weave:
950
raise errors.NoSuchRevision(self, revision_id)
952
# add what can be reached from revision_id
954
pending = set([revision_id])
955
while len(pending) > 0:
957
result[node] = a_weave.get_parents(node)
958
for revision_id in result[node]:
959
if revision_id not in result:
960
pending.add(revision_id)
964
def get_revision_graph_with_ghosts(self, revision_ids=None):
965
"""Return a graph of the revisions with ghosts marked as applicable.
967
:param revision_ids: an iterable of revisions to graph or None for all.
968
:return: a Graph object with the graph reachable from revision_ids.
970
result = graph.Graph()
971
vf = self._get_revision_vf()
972
versions = set(vf.versions())
974
pending = set(self.all_revision_ids())
977
pending = set(revision_ids)
978
# special case NULL_REVISION
979
if _mod_revision.NULL_REVISION in pending:
980
pending.remove(_mod_revision.NULL_REVISION)
981
required = set(pending)
984
revision_id = pending.pop()
985
if not revision_id in versions:
986
if revision_id in required:
987
raise errors.NoSuchRevision(self, revision_id)
989
result.add_ghost(revision_id)
990
# mark it as done so we don't try for it again.
991
done.add(revision_id)
993
parent_ids = vf.get_parents_with_ghosts(revision_id)
994
for parent_id in parent_ids:
995
# is this queued or done ?
996
if (parent_id not in pending and
997
parent_id not in done):
999
pending.add(parent_id)
1000
result.add_node(revision_id, parent_ids)
1001
done.add(revision_id)
1004
def _get_revision_vf(self):
1005
""":return: a versioned file containing the revisions."""
1006
vf = self._revision_store.get_revision_file(self.get_transaction())
1010
def reconcile(self, other=None, thorough=False):
1011
"""Reconcile this repository."""
1012
from bzrlib.reconcile import KnitReconciler
1013
reconciler = KnitReconciler(self, thorough=thorough)
1014
reconciler.reconcile()
1017
def revision_parents(self, revision_id):
1018
return self._get_revision_vf().get_parents(revision_id)
1021
class RepositoryFormatRegistry(registry.Registry):
1022
"""Registry of RepositoryFormats.
1026
format_registry = RepositoryFormatRegistry()
1027
"""Registry of formats, indexed by their identifying format string."""
1030
class RepositoryFormat(object):
1031
"""A repository format.
1033
Formats provide three things:
1034
* An initialization routine to construct repository data on disk.
1035
* a format string which is used when the BzrDir supports versioned
1037
* an open routine which returns a Repository instance.
1039
Formats are placed in an dict by their format string for reference
1040
during opening. These should be subclasses of RepositoryFormat
1043
Once a format is deprecated, just deprecate the initialize and open
1044
methods on the format class. Do not deprecate the object, as the
1045
object will be created every system load.
1047
Common instance attributes:
1048
_matchingbzrdir - the bzrdir format that the repository format was
1049
originally written to work with. This can be used if manually
1050
constructing a bzrdir and repository, or more commonly for test suite
1055
return "<%s>" % self.__class__.__name__
1058
def find_format(klass, a_bzrdir):
1059
"""Return the format for the repository object in a_bzrdir.
1061
This is used by bzr native formats that have a "format" file in
1062
the repository. Other methods may be used by different types of
1066
transport = a_bzrdir.get_repository_transport(None)
1067
format_string = transport.get("format").read()
1068
return format_registry.get(format_string)
1069
except errors.NoSuchFile:
1070
raise errors.NoRepositoryPresent(a_bzrdir)
1072
raise errors.UnknownFormatError(format=format_string)
1075
@deprecated_method(symbol_versioning.zero_fourteen)
1076
def set_default_format(klass, format):
1077
klass._set_default_format(format)
1080
def _set_default_format(klass, format):
1081
"""Set the default format for new Repository creation.
1083
The format must already be registered.
1085
format_registry.default_key = format.get_format_string()
1088
def register_format(klass, format):
1089
format_registry.register(format.get_format_string(), format)
1092
def unregister_format(klass, format):
1093
format_registry.remove(format.get_format_string())
1096
def get_default_format(klass):
1097
"""Return the current default format."""
1098
return format_registry.get(format_registry.default_key)
1100
def _get_control_store(self, repo_transport, control_files):
1101
"""Return the control store for this repository."""
1102
raise NotImplementedError(self._get_control_store)
1104
def get_format_string(self):
1105
"""Return the ASCII format string that identifies this format.
1107
Note that in pre format ?? repositories the format string is
1108
not permitted nor written to disk.
1110
raise NotImplementedError(self.get_format_string)
1112
def get_format_description(self):
1113
"""Return the short description for this format."""
1114
raise NotImplementedError(self.get_format_description)
1116
def _get_revision_store(self, repo_transport, control_files):
1117
"""Return the revision store object for this a_bzrdir."""
1118
raise NotImplementedError(self._get_revision_store)
1120
def _get_text_rev_store(self,
1127
"""Common logic for getting a revision store for a repository.
1129
see self._get_revision_store for the subclass-overridable method to
1130
get the store for a repository.
1132
from bzrlib.store.revision.text import TextRevisionStore
1133
dir_mode = control_files._dir_mode
1134
file_mode = control_files._file_mode
1135
text_store =TextStore(transport.clone(name),
1137
compressed=compressed,
1139
file_mode=file_mode)
1140
_revision_store = TextRevisionStore(text_store, serializer)
1141
return _revision_store
1143
def _get_versioned_file_store(self,
1148
versionedfile_class=weave.WeaveFile,
1149
versionedfile_kwargs={},
1151
weave_transport = control_files._transport.clone(name)
1152
dir_mode = control_files._dir_mode
1153
file_mode = control_files._file_mode
1154
return VersionedFileStore(weave_transport, prefixed=prefixed,
1156
file_mode=file_mode,
1157
versionedfile_class=versionedfile_class,
1158
versionedfile_kwargs=versionedfile_kwargs,
1161
def initialize(self, a_bzrdir, shared=False):
1162
"""Initialize a repository of this format in a_bzrdir.
1164
:param a_bzrdir: The bzrdir to put the new repository in it.
1165
:param shared: The repository should be initialized as a sharable one.
1167
This may raise UninitializableFormat if shared repository are not
1168
compatible the a_bzrdir.
1171
def is_supported(self):
1172
"""Is this format supported?
1174
Supported formats must be initializable and openable.
1175
Unsupported formats may not support initialization or committing or
1176
some other features depending on the reason for not being supported.
1180
def check_conversion_target(self, target_format):
1181
raise NotImplementedError(self.check_conversion_target)
1183
def open(self, a_bzrdir, _found=False):
1184
"""Return an instance of this format for the bzrdir a_bzrdir.
1186
_found is a private parameter, do not use it.
1188
raise NotImplementedError(self.open)
1191
class MetaDirRepositoryFormat(RepositoryFormat):
1192
"""Common base class for the new repositories using the metadir layout."""
1194
rich_root_data = False
1197
super(MetaDirRepositoryFormat, self).__init__()
1198
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1200
def _create_control_files(self, a_bzrdir):
1201
"""Create the required files and the initial control_files object."""
1202
# FIXME: RBC 20060125 don't peek under the covers
1203
# NB: no need to escape relative paths that are url safe.
1204
repository_transport = a_bzrdir.get_repository_transport(self)
1205
control_files = lockable_files.LockableFiles(repository_transport,
1206
'lock', lockdir.LockDir)
1207
control_files.create_lock()
1208
return control_files
1210
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1211
"""Upload the initial blank content."""
1212
control_files = self._create_control_files(a_bzrdir)
1213
control_files.lock_write()
1215
control_files._transport.mkdir_multi(dirs,
1216
mode=control_files._dir_mode)
1217
for file, content in files:
1218
control_files.put(file, content)
1219
for file, content in utf8_files:
1220
control_files.put_utf8(file, content)
1222
control_files.put_utf8('shared-storage', '')
1224
control_files.unlock()
1227
class RepositoryFormatKnit(MetaDirRepositoryFormat):
1228
"""Bzr repository knit format (generalized).
1230
This repository format has:
1231
- knits for file texts and inventory
1232
- hash subdirectory based stores.
1233
- knits for revisions and signatures
1234
- TextStores for revisions and signatures.
1235
- a format marker of its own
1236
- an optional 'shared-storage' flag
1237
- an optional 'no-working-trees' flag
1241
def _get_control_store(self, repo_transport, control_files):
1242
"""Return the control store for this repository."""
1243
return VersionedFileStore(
1246
file_mode=control_files._file_mode,
1247
versionedfile_class=knit.KnitVersionedFile,
1248
versionedfile_kwargs={'factory':knit.KnitPlainFactory()},
1251
def _get_revision_store(self, repo_transport, control_files):
1252
"""See RepositoryFormat._get_revision_store()."""
1253
from bzrlib.store.revision.knit import KnitRevisionStore
1254
versioned_file_store = VersionedFileStore(
1256
file_mode=control_files._file_mode,
1259
versionedfile_class=knit.KnitVersionedFile,
1260
versionedfile_kwargs={'delta':False,
1261
'factory':knit.KnitPlainFactory(),
1265
return KnitRevisionStore(versioned_file_store)
1267
def _get_text_store(self, transport, control_files):
1268
"""See RepositoryFormat._get_text_store()."""
1269
return self._get_versioned_file_store('knits',
1272
versionedfile_class=knit.KnitVersionedFile,
1273
versionedfile_kwargs={
1274
'create_parent_dir':True,
1275
'delay_create':True,
1276
'dir_mode':control_files._dir_mode,
1280
def initialize(self, a_bzrdir, shared=False):
1281
"""Create a knit format 1 repository.
1283
:param a_bzrdir: bzrdir to contain the new repository; must already
1285
:param shared: If true the repository will be initialized as a shared
1288
mutter('creating repository in %s.', a_bzrdir.transport.base)
1289
dirs = ['revision-store', 'knits']
1291
utf8_files = [('format', self.get_format_string())]
1293
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1294
repo_transport = a_bzrdir.get_repository_transport(None)
1295
control_files = lockable_files.LockableFiles(repo_transport,
1296
'lock', lockdir.LockDir)
1297
control_store = self._get_control_store(repo_transport, control_files)
1298
transaction = transactions.WriteTransaction()
1299
# trigger a write of the inventory store.
1300
control_store.get_weave_or_empty('inventory', transaction)
1301
_revision_store = self._get_revision_store(repo_transport, control_files)
1302
# the revision id here is irrelevant: it will not be stored, and cannot
1304
_revision_store.has_revision_id('A', transaction)
1305
_revision_store.get_signature_file(transaction)
1306
return self.open(a_bzrdir=a_bzrdir, _found=True)
1308
def open(self, a_bzrdir, _found=False, _override_transport=None):
1309
"""See RepositoryFormat.open().
1311
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1312
repository at a slightly different url
1313
than normal. I.e. during 'upgrade'.
1316
format = RepositoryFormat.find_format(a_bzrdir)
1317
assert format.__class__ == self.__class__
1318
if _override_transport is not None:
1319
repo_transport = _override_transport
1321
repo_transport = a_bzrdir.get_repository_transport(None)
1322
control_files = lockable_files.LockableFiles(repo_transport,
1323
'lock', lockdir.LockDir)
1324
text_store = self._get_text_store(repo_transport, control_files)
1325
control_store = self._get_control_store(repo_transport, control_files)
1326
_revision_store = self._get_revision_store(repo_transport, control_files)
1327
return KnitRepository(_format=self,
1329
control_files=control_files,
1330
_revision_store=_revision_store,
1331
control_store=control_store,
1332
text_store=text_store)
1335
class RepositoryFormatKnit1(RepositoryFormatKnit):
1336
"""Bzr repository knit format 1.
1338
This repository format has:
1339
- knits for file texts and inventory
1340
- hash subdirectory based stores.
1341
- knits for revisions and signatures
1342
- TextStores for revisions and signatures.
1343
- a format marker of its own
1344
- an optional 'shared-storage' flag
1345
- an optional 'no-working-trees' flag
1348
This format was introduced in bzr 0.8.
1350
def get_format_string(self):
1351
"""See RepositoryFormat.get_format_string()."""
1352
return "Bazaar-NG Knit Repository Format 1"
1354
def get_format_description(self):
1355
"""See RepositoryFormat.get_format_description()."""
1356
return "Knit repository format 1"
1358
def check_conversion_target(self, target_format):
1362
# formats which have no format string are not discoverable
1363
# and not independently creatable, so are not registered. They're
1364
# all in bzrlib.repofmt.weaverepo now.
1365
format_registry.register_lazy(
1366
'Bazaar-NG Repository format 7',
1367
'bzrlib.repofmt.weaverepo',
1368
'RepositoryFormat7_instance'
1370
# KEEP in sync with bzrdir.format_registry default, which controls the overall
1371
# default control directory format
1372
_default_format = RepositoryFormatKnit1()
1373
RepositoryFormat.register_format(_default_format)
1374
format_registry.register_lazy(
1375
'Bazaar Knit Repository Format 2\n',
1376
'bzrlib.repofmt.knitrepo',
1377
'RepositoryFormatKnit2_instance',
1379
RepositoryFormat._set_default_format(_default_format)
1382
class InterRepository(InterObject):
1383
"""This class represents operations taking place between two repositories.
1385
Its instances have methods like copy_content and fetch, and contain
1386
references to the source and target repositories these operations can be
1389
Often we will provide convenience methods on 'repository' which carry out
1390
operations with another repository - they will always forward to
1391
InterRepository.get(other).method_name(parameters).
1395
"""The available optimised InterRepository types."""
1397
def copy_content(self, revision_id=None, basis=None):
1398
raise NotImplementedError(self.copy_content)
1400
def fetch(self, revision_id=None, pb=None):
1401
"""Fetch the content required to construct revision_id.
1403
The content is copied from self.source to self.target.
1405
:param revision_id: if None all content is copied, if NULL_REVISION no
1407
:param pb: optional progress bar to use for progress reports. If not
1408
provided a default one will be created.
1410
Returns the copied revision count and the failed revisions in a tuple:
1413
raise NotImplementedError(self.fetch)
1416
def missing_revision_ids(self, revision_id=None):
1417
"""Return the revision ids that source has that target does not.
1419
These are returned in topological order.
1421
:param revision_id: only return revision ids included by this
1424
# generic, possibly worst case, slow code path.
1425
target_ids = set(self.target.all_revision_ids())
1426
if revision_id is not None:
1427
source_ids = self.source.get_ancestry(revision_id)
1428
assert source_ids[0] is None
1431
source_ids = self.source.all_revision_ids()
1432
result_set = set(source_ids).difference(target_ids)
1433
# this may look like a no-op: its not. It preserves the ordering
1434
# other_ids had while only returning the members from other_ids
1435
# that we've decided we need.
1436
return [rev_id for rev_id in source_ids if rev_id in result_set]
1439
class InterSameDataRepository(InterRepository):
1440
"""Code for converting between repositories that represent the same data.
1442
Data format and model must match for this to work.
1445
_matching_repo_format = _default_format
1446
"""Repository format for testing with."""
1449
def is_compatible(source, target):
1450
if not isinstance(source, Repository):
1452
if not isinstance(target, Repository):
1454
if source._format.rich_root_data == target._format.rich_root_data:
1460
def copy_content(self, revision_id=None, basis=None):
1461
"""Make a complete copy of the content in self into destination.
1463
This is a destructive operation! Do not use it on existing
1466
:param revision_id: Only copy the content needed to construct
1467
revision_id and its parents.
1468
:param basis: Copy the needed data preferentially from basis.
1471
self.target.set_make_working_trees(self.source.make_working_trees())
1472
except NotImplementedError:
1474
# grab the basis available data
1475
if basis is not None:
1476
self.target.fetch(basis, revision_id=revision_id)
1477
# but don't bother fetching if we have the needed data now.
1478
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1479
self.target.has_revision(revision_id)):
1481
self.target.fetch(self.source, revision_id=revision_id)
1484
def fetch(self, revision_id=None, pb=None):
1485
"""See InterRepository.fetch()."""
1486
from bzrlib.fetch import GenericRepoFetcher
1487
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1488
self.source, self.source._format, self.target,
1489
self.target._format)
1490
f = GenericRepoFetcher(to_repository=self.target,
1491
from_repository=self.source,
1492
last_revision=revision_id,
1494
return f.count_copied, f.failed_revisions
1497
class InterKnitRepo(InterSameDataRepository):
1498
"""Optimised code paths between Knit based repositories."""
1500
_matching_repo_format = RepositoryFormatKnit1()
1501
"""Repository format for testing with."""
1504
def is_compatible(source, target):
1505
"""Be compatible with known Knit formats.
1507
We don't test for the stores being of specific types because that
1508
could lead to confusing results, and there is no need to be
1512
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1513
isinstance(target._format, (RepositoryFormatKnit1)))
1514
except AttributeError:
1518
def fetch(self, revision_id=None, pb=None):
1519
"""See InterRepository.fetch()."""
1520
from bzrlib.fetch import KnitRepoFetcher
1521
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1522
self.source, self.source._format, self.target, self.target._format)
1523
f = KnitRepoFetcher(to_repository=self.target,
1524
from_repository=self.source,
1525
last_revision=revision_id,
1527
return f.count_copied, f.failed_revisions
1530
def missing_revision_ids(self, revision_id=None):
1531
"""See InterRepository.missing_revision_ids()."""
1532
if revision_id is not None:
1533
source_ids = self.source.get_ancestry(revision_id)
1534
assert source_ids[0] is None
1537
source_ids = self.source._all_possible_ids()
1538
source_ids_set = set(source_ids)
1539
# source_ids is the worst possible case we may need to pull.
1540
# now we want to filter source_ids against what we actually
1541
# have in target, but don't try to check for existence where we know
1542
# we do not have a revision as that would be pointless.
1543
target_ids = set(self.target._all_possible_ids())
1544
possibly_present_revisions = target_ids.intersection(source_ids_set)
1545
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1546
required_revisions = source_ids_set.difference(actually_present_revisions)
1547
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1548
if revision_id is not None:
1549
# we used get_ancestry to determine source_ids then we are assured all
1550
# revisions referenced are present as they are installed in topological order.
1551
# and the tip revision was validated by get_ancestry.
1552
return required_topo_revisions
1554
# if we just grabbed the possibly available ids, then
1555
# we only have an estimate of whats available and need to validate
1556
# that against the revision records.
1557
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1560
class InterModel1and2(InterRepository):
1562
_matching_repo_format = None
1565
def is_compatible(source, target):
1566
if not isinstance(source, Repository):
1568
if not isinstance(target, Repository):
1570
if not source._format.rich_root_data and target._format.rich_root_data:
1576
def fetch(self, revision_id=None, pb=None):
1577
"""See InterRepository.fetch()."""
1578
from bzrlib.fetch import Model1toKnit2Fetcher
1579
f = Model1toKnit2Fetcher(to_repository=self.target,
1580
from_repository=self.source,
1581
last_revision=revision_id,
1583
return f.count_copied, f.failed_revisions
1586
def copy_content(self, revision_id=None, basis=None):
1587
"""Make a complete copy of the content in self into destination.
1589
This is a destructive operation! Do not use it on existing
1592
:param revision_id: Only copy the content needed to construct
1593
revision_id and its parents.
1594
:param basis: Copy the needed data preferentially from basis.
1597
self.target.set_make_working_trees(self.source.make_working_trees())
1598
except NotImplementedError:
1600
# grab the basis available data
1601
if basis is not None:
1602
self.target.fetch(basis, revision_id=revision_id)
1603
# but don't bother fetching if we have the needed data now.
1604
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1605
self.target.has_revision(revision_id)):
1607
self.target.fetch(self.source, revision_id=revision_id)
1610
class InterKnit1and2(InterKnitRepo):
1612
_matching_repo_format = None
1615
def is_compatible(source, target):
1616
"""Be compatible with Knit1 source and Knit2 target"""
1617
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit2
1619
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1620
isinstance(target._format, (RepositoryFormatKnit2)))
1621
except AttributeError:
1625
def fetch(self, revision_id=None, pb=None):
1626
"""See InterRepository.fetch()."""
1627
from bzrlib.fetch import Knit1to2Fetcher
1628
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1629
self.source, self.source._format, self.target,
1630
self.target._format)
1631
f = Knit1to2Fetcher(to_repository=self.target,
1632
from_repository=self.source,
1633
last_revision=revision_id,
1635
return f.count_copied, f.failed_revisions
1638
InterRepository.register_optimiser(InterSameDataRepository)
1639
InterRepository.register_optimiser(InterKnitRepo)
1640
InterRepository.register_optimiser(InterModel1and2)
1641
InterRepository.register_optimiser(InterKnit1and2)
1644
class RepositoryTestProviderAdapter(object):
1645
"""A tool to generate a suite testing multiple repository formats at once.
1647
This is done by copying the test once for each transport and injecting
1648
the transport_server, transport_readonly_server, and bzrdir_format and
1649
repository_format classes into each copy. Each copy is also given a new id()
1650
to make it easy to identify.
1653
def __init__(self, transport_server, transport_readonly_server, formats):
1654
self._transport_server = transport_server
1655
self._transport_readonly_server = transport_readonly_server
1656
self._formats = formats
1658
def adapt(self, test):
1659
result = unittest.TestSuite()
1660
for repository_format, bzrdir_format in self._formats:
1661
new_test = deepcopy(test)
1662
new_test.transport_server = self._transport_server
1663
new_test.transport_readonly_server = self._transport_readonly_server
1664
new_test.bzrdir_format = bzrdir_format
1665
new_test.repository_format = repository_format
1666
def make_new_test_id():
1667
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1668
return lambda: new_id
1669
new_test.id = make_new_test_id()
1670
result.addTest(new_test)
1674
class InterRepositoryTestProviderAdapter(object):
1675
"""A tool to generate a suite testing multiple inter repository formats.
1677
This is done by copying the test once for each interrepo provider and injecting
1678
the transport_server, transport_readonly_server, repository_format and
1679
repository_to_format classes into each copy.
1680
Each copy is also given a new id() to make it easy to identify.
1683
def __init__(self, transport_server, transport_readonly_server, formats):
1684
self._transport_server = transport_server
1685
self._transport_readonly_server = transport_readonly_server
1686
self._formats = formats
1688
def adapt(self, test):
1689
result = unittest.TestSuite()
1690
for interrepo_class, repository_format, repository_format_to in self._formats:
1691
new_test = deepcopy(test)
1692
new_test.transport_server = self._transport_server
1693
new_test.transport_readonly_server = self._transport_readonly_server
1694
new_test.interrepo_class = interrepo_class
1695
new_test.repository_format = repository_format
1696
new_test.repository_format_to = repository_format_to
1697
def make_new_test_id():
1698
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1699
return lambda: new_id
1700
new_test.id = make_new_test_id()
1701
result.addTest(new_test)
1705
def default_test_list():
1706
"""Generate the default list of interrepo permutations to test."""
1707
from bzrlib.repofmt import knitrepo, weaverepo
1709
# test the default InterRepository between format 6 and the current
1711
# XXX: robertc 20060220 reinstate this when there are two supported
1712
# formats which do not have an optimal code path between them.
1713
#result.append((InterRepository,
1714
# RepositoryFormat6(),
1715
# RepositoryFormatKnit1()))
1716
for optimiser in InterRepository._optimisers:
1717
if optimiser._matching_repo_format is not None:
1718
result.append((optimiser,
1719
optimiser._matching_repo_format,
1720
optimiser._matching_repo_format
1722
# if there are specific combinations we want to use, we can add them
1724
result.append((InterModel1and2,
1725
weaverepo.RepositoryFormat5(),
1726
knitrepo.RepositoryFormatKnit2()))
1727
result.append((InterKnit1and2, RepositoryFormatKnit1(),
1728
knitrepo.RepositoryFormatKnit2()))
1732
class CopyConverter(object):
1733
"""A repository conversion tool which just performs a copy of the content.
1735
This is slow but quite reliable.
1738
def __init__(self, target_format):
1739
"""Create a CopyConverter.
1741
:param target_format: The format the resulting repository should be.
1743
self.target_format = target_format
1745
def convert(self, repo, pb):
1746
"""Perform the conversion of to_convert, giving feedback via pb.
1748
:param to_convert: The disk object to convert.
1749
:param pb: a progress bar to use for progress information.
1754
# this is only useful with metadir layouts - separated repo content.
1755
# trigger an assertion if not such
1756
repo._format.get_format_string()
1757
self.repo_dir = repo.bzrdir
1758
self.step('Moving repository to repository.backup')
1759
self.repo_dir.transport.move('repository', 'repository.backup')
1760
backup_transport = self.repo_dir.transport.clone('repository.backup')
1761
repo._format.check_conversion_target(self.target_format)
1762
self.source_repo = repo._format.open(self.repo_dir,
1764
_override_transport=backup_transport)
1765
self.step('Creating new repository')
1766
converted = self.target_format.initialize(self.repo_dir,
1767
self.source_repo.is_shared())
1768
converted.lock_write()
1770
self.step('Copying content into repository.')
1771
self.source_repo.copy_content_into(converted)
1774
self.step('Deleting old repository content.')
1775
self.repo_dir.transport.delete_tree('repository.backup')
1776
self.pb.note('repository converted')
1778
def step(self, message):
1779
"""Update the pb by a step."""
1781
self.pb.update(message, self.count, self.total)
1784
class CommitBuilder(object):
1785
"""Provides an interface to build up a commit.
1787
This allows describing a tree to be committed without needing to
1788
know the internals of the format of the repository.
1791
record_root_entry = False
1792
def __init__(self, repository, parents, config, timestamp=None,
1793
timezone=None, committer=None, revprops=None,
1795
"""Initiate a CommitBuilder.
1797
:param repository: Repository to commit to.
1798
:param parents: Revision ids of the parents of the new revision.
1799
:param config: Configuration to use.
1800
:param timestamp: Optional timestamp recorded for commit.
1801
:param timezone: Optional timezone for timestamp.
1802
:param committer: Optional committer to set for commit.
1803
:param revprops: Optional dictionary of revision properties.
1804
:param revision_id: Optional revision id.
1806
self._config = config
1808
if committer is None:
1809
self._committer = self._config.username()
1811
assert isinstance(committer, basestring), type(committer)
1812
self._committer = committer
1814
self.new_inventory = Inventory(None)
1815
self._new_revision_id = revision_id
1816
self.parents = parents
1817
self.repository = repository
1820
if revprops is not None:
1821
self._revprops.update(revprops)
1823
if timestamp is None:
1824
timestamp = time.time()
1825
# Restrict resolution to 1ms
1826
self._timestamp = round(timestamp, 3)
1828
if timezone is None:
1829
self._timezone = local_time_offset()
1831
self._timezone = int(timezone)
1833
self._generate_revision_if_needed()
1835
def commit(self, message):
1836
"""Make the actual commit.
1838
:return: The revision id of the recorded revision.
1840
rev = _mod_revision.Revision(
1841
timestamp=self._timestamp,
1842
timezone=self._timezone,
1843
committer=self._committer,
1845
inventory_sha1=self.inv_sha1,
1846
revision_id=self._new_revision_id,
1847
properties=self._revprops)
1848
rev.parent_ids = self.parents
1849
self.repository.add_revision(self._new_revision_id, rev,
1850
self.new_inventory, self._config)
1851
return self._new_revision_id
1853
def revision_tree(self):
1854
"""Return the tree that was just committed.
1856
After calling commit() this can be called to get a RevisionTree
1857
representing the newly committed tree. This is preferred to
1858
calling Repository.revision_tree() because that may require
1859
deserializing the inventory, while we already have a copy in
1862
return RevisionTree(self.repository, self.new_inventory,
1863
self._new_revision_id)
1865
def finish_inventory(self):
1866
"""Tell the builder that the inventory is finished."""
1867
if self.new_inventory.root is None:
1868
symbol_versioning.warn('Root entry should be supplied to'
1869
' record_entry_contents, as of bzr 0.10.',
1870
DeprecationWarning, stacklevel=2)
1871
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
1872
self.new_inventory.revision_id = self._new_revision_id
1873
self.inv_sha1 = self.repository.add_inventory(
1874
self._new_revision_id,
1879
def _gen_revision_id(self):
1880
"""Return new revision-id."""
1881
return generate_ids.gen_revision_id(self._config.username(),
1884
def _generate_revision_if_needed(self):
1885
"""Create a revision id if None was supplied.
1887
If the repository can not support user-specified revision ids
1888
they should override this function and raise CannotSetRevisionId
1889
if _new_revision_id is not None.
1891
:raises: CannotSetRevisionId
1893
if self._new_revision_id is None:
1894
self._new_revision_id = self._gen_revision_id()
1896
def record_entry_contents(self, ie, parent_invs, path, tree):
1897
"""Record the content of ie from tree into the commit if needed.
1899
Side effect: sets ie.revision when unchanged
1901
:param ie: An inventory entry present in the commit.
1902
:param parent_invs: The inventories of the parent revisions of the
1904
:param path: The path the entry is at in the tree.
1905
:param tree: The tree which contains this entry and should be used to
1908
if self.new_inventory.root is None and ie.parent_id is not None:
1909
symbol_versioning.warn('Root entry should be supplied to'
1910
' record_entry_contents, as of bzr 0.10.',
1911
DeprecationWarning, stacklevel=2)
1912
self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
1914
self.new_inventory.add(ie)
1916
# ie.revision is always None if the InventoryEntry is considered
1917
# for committing. ie.snapshot will record the correct revision
1918
# which may be the sole parent if it is untouched.
1919
if ie.revision is not None:
1922
# In this revision format, root entries have no knit or weave
1923
if ie is self.new_inventory.root:
1924
# When serializing out to disk and back in
1925
# root.revision is always _new_revision_id
1926
ie.revision = self._new_revision_id
1928
previous_entries = ie.find_previous_heads(
1930
self.repository.weave_store,
1931
self.repository.get_transaction())
1932
# we are creating a new revision for ie in the history store
1934
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
1936
def modified_directory(self, file_id, file_parents):
1937
"""Record the presence of a symbolic link.
1939
:param file_id: The file_id of the link to record.
1940
:param file_parents: The per-file parent revision ids.
1942
self._add_text_to_weave(file_id, [], file_parents.keys())
1944
def modified_file_text(self, file_id, file_parents,
1945
get_content_byte_lines, text_sha1=None,
1947
"""Record the text of file file_id
1949
:param file_id: The file_id of the file to record the text of.
1950
:param file_parents: The per-file parent revision ids.
1951
:param get_content_byte_lines: A callable which will return the byte
1953
:param text_sha1: Optional SHA1 of the file contents.
1954
:param text_size: Optional size of the file contents.
1956
# mutter('storing text of file {%s} in revision {%s} into %r',
1957
# file_id, self._new_revision_id, self.repository.weave_store)
1958
# special case to avoid diffing on renames or
1960
if (len(file_parents) == 1
1961
and text_sha1 == file_parents.values()[0].text_sha1
1962
and text_size == file_parents.values()[0].text_size):
1963
previous_ie = file_parents.values()[0]
1964
versionedfile = self.repository.weave_store.get_weave(file_id,
1965
self.repository.get_transaction())
1966
versionedfile.clone_text(self._new_revision_id,
1967
previous_ie.revision, file_parents.keys())
1968
return text_sha1, text_size
1970
new_lines = get_content_byte_lines()
1971
# TODO: Rather than invoking sha_strings here, _add_text_to_weave
1972
# should return the SHA1 and size
1973
self._add_text_to_weave(file_id, new_lines, file_parents.keys())
1974
return osutils.sha_strings(new_lines), \
1975
sum(map(len, new_lines))
1977
def modified_link(self, file_id, file_parents, link_target):
1978
"""Record the presence of a symbolic link.
1980
:param file_id: The file_id of the link to record.
1981
:param file_parents: The per-file parent revision ids.
1982
:param link_target: Target location of this link.
1984
self._add_text_to_weave(file_id, [], file_parents.keys())
1986
def _add_text_to_weave(self, file_id, new_lines, parents):
1987
versionedfile = self.repository.weave_store.get_weave_or_empty(
1988
file_id, self.repository.get_transaction())
1989
versionedfile.add_lines(self._new_revision_id, parents, new_lines)
1990
versionedfile.clear_cache()
1993
class _CommitBuilder(CommitBuilder):
1994
"""Temporary class so old CommitBuilders are detected properly
1996
Note: CommitBuilder works whether or not root entry is recorded.
1999
record_root_entry = True
2002
class RootCommitBuilder(CommitBuilder):
2003
"""This commitbuilder actually records the root id"""
2005
record_root_entry = True
2007
def record_entry_contents(self, ie, parent_invs, path, tree):
2008
"""Record the content of ie from tree into the commit if needed.
2010
Side effect: sets ie.revision when unchanged
2012
:param ie: An inventory entry present in the commit.
2013
:param parent_invs: The inventories of the parent revisions of the
2015
:param path: The path the entry is at in the tree.
2016
:param tree: The tree which contains this entry and should be used to
2019
assert self.new_inventory.root is not None or ie.parent_id is None
2020
self.new_inventory.add(ie)
2022
# ie.revision is always None if the InventoryEntry is considered
2023
# for committing. ie.snapshot will record the correct revision
2024
# which may be the sole parent if it is untouched.
2025
if ie.revision is not None:
2028
previous_entries = ie.find_previous_heads(
2030
self.repository.weave_store,
2031
self.repository.get_transaction())
2032
# we are creating a new revision for ie in the history store
2034
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2046
def _unescaper(match, _map=_unescape_map):
2047
return _map[match.group(1)]
2053
def _unescape_xml(data):
2054
"""Unescape predefined XML entities in a string of data."""
2056
if _unescape_re is None:
2057
_unescape_re = re.compile('\&([^;]*);')
2058
return _unescape_re.sub(_unescaper, data)