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
class Repository(object):
64
"""Repository holding history for one or more branches.
66
The repository holds and retrieves historical information including
67
revisions and file history. It's normally accessed only by the Branch,
68
which views a particular line of development through that history.
70
The Repository builds on top of Stores and a Transport, which respectively
71
describe the disk data format and the way of accessing the (possibly
75
_file_ids_altered_regex = lazy_regex.lazy_compile(
76
r'file_id="(?P<file_id>[^"]+)"'
77
r'.*revision="(?P<revision_id>[^"]+)"'
81
def add_inventory(self, revid, inv, parents):
82
"""Add the inventory inv to the repository as revid.
84
:param parents: The revision ids of the parents that revid
85
is known to have and are in the repository already.
87
returns the sha1 of the serialized inventory.
89
_mod_revision.check_not_reserved_id(revid)
90
assert inv.revision_id is None or inv.revision_id == revid, \
91
"Mismatch between inventory revision" \
92
" id and insertion revid (%r, %r)" % (inv.revision_id, revid)
93
assert inv.root is not None
94
inv_text = self.serialise_inventory(inv)
95
inv_sha1 = osutils.sha_string(inv_text)
96
inv_vf = self.control_weaves.get_weave('inventory',
97
self.get_transaction())
98
self._inventory_add_lines(inv_vf, revid, parents, osutils.split_lines(inv_text))
101
def _inventory_add_lines(self, inv_vf, revid, parents, lines):
103
for parent in parents:
105
final_parents.append(parent)
107
inv_vf.add_lines(revid, final_parents, lines)
110
def add_revision(self, rev_id, rev, inv=None, config=None):
111
"""Add rev to the revision store as rev_id.
113
:param rev_id: the revision id to use.
114
:param rev: The revision object.
115
:param inv: The inventory for the revision. if None, it will be looked
116
up in the inventory storer
117
:param config: If None no digital signature will be created.
118
If supplied its signature_needed method will be used
119
to determine if a signature should be made.
121
_mod_revision.check_not_reserved_id(rev_id)
122
if config is not None and config.signature_needed():
124
inv = self.get_inventory(rev_id)
125
plaintext = Testament(rev, inv).as_short_text()
126
self.store_revision_signature(
127
gpg.GPGStrategy(config), plaintext, rev_id)
128
if not rev_id in self.get_inventory_weave():
130
raise errors.WeaveRevisionNotPresent(rev_id,
131
self.get_inventory_weave())
133
# yes, this is not suitable for adding with ghosts.
134
self.add_inventory(rev_id, inv, rev.parent_ids)
135
self._revision_store.add_revision(rev, self.get_transaction())
138
def _all_possible_ids(self):
139
"""Return all the possible revisions that we could find."""
140
return self.get_inventory_weave().versions()
142
def all_revision_ids(self):
143
"""Returns a list of all the revision ids in the repository.
145
This is deprecated because code should generally work on the graph
146
reachable from a particular revision, and ignore any other revisions
147
that might be present. There is no direct replacement method.
149
return self._all_revision_ids()
152
def _all_revision_ids(self):
153
"""Returns a list of all the revision ids in the repository.
155
These are in as much topological order as the underlying store can
156
present: for weaves ghosts may lead to a lack of correctness until
157
the reweave updates the parents list.
159
if self._revision_store.text_store.listable():
160
return self._revision_store.all_revision_ids(self.get_transaction())
161
result = self._all_possible_ids()
162
return self._eliminate_revisions_not_present(result)
164
def break_lock(self):
165
"""Break a lock if one is present from another instance.
167
Uses the ui factory to ask for confirmation if the lock may be from
170
self.control_files.break_lock()
173
def _eliminate_revisions_not_present(self, revision_ids):
174
"""Check every revision id in revision_ids to see if we have it.
176
Returns a set of the present revisions.
179
for id in revision_ids:
180
if self.has_revision(id):
185
def create(a_bzrdir):
186
"""Construct the current default format repository in a_bzrdir."""
187
return RepositoryFormat.get_default_format().initialize(a_bzrdir)
189
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
190
"""instantiate a Repository.
192
:param _format: The format of the repository on disk.
193
:param a_bzrdir: The BzrDir of the repository.
195
In the future we will have a single api for all stores for
196
getting file texts, inventories and revisions, then
197
this construct will accept instances of those things.
199
super(Repository, self).__init__()
200
self._format = _format
201
# the following are part of the public API for Repository:
202
self.bzrdir = a_bzrdir
203
self.control_files = control_files
204
self._revision_store = _revision_store
205
self.text_store = text_store
206
# backwards compatibility
207
self.weave_store = text_store
208
# not right yet - should be more semantically clear ?
210
self.control_store = control_store
211
self.control_weaves = control_store
212
# TODO: make sure to construct the right store classes, etc, depending
213
# on whether escaping is required.
214
self._warn_if_deprecated()
217
return '%s(%r)' % (self.__class__.__name__,
218
self.bzrdir.transport.base)
221
return self.control_files.is_locked()
223
def lock_write(self):
224
self.control_files.lock_write()
227
self.control_files.lock_read()
229
def get_physical_lock_status(self):
230
return self.control_files.get_physical_lock_status()
233
def missing_revision_ids(self, other, revision_id=None):
234
"""Return the revision ids that other has that this does not.
236
These are returned in topological order.
238
revision_id: only return revision ids included by revision_id.
240
return InterRepository.get(other, self).missing_revision_ids(revision_id)
244
"""Open the repository rooted at base.
246
For instance, if the repository is at URL/.bzr/repository,
247
Repository.open(URL) -> a Repository instance.
249
control = bzrdir.BzrDir.open(base)
250
return control.open_repository()
252
def copy_content_into(self, destination, revision_id=None, basis=None):
253
"""Make a complete copy of the content in self into destination.
255
This is a destructive operation! Do not use it on existing
258
return InterRepository.get(self, destination).copy_content(revision_id, basis)
260
def fetch(self, source, revision_id=None, pb=None):
261
"""Fetch the content required to construct revision_id from source.
263
If revision_id is None all content is copied.
265
return InterRepository.get(source, self).fetch(revision_id=revision_id,
268
def get_commit_builder(self, branch, parents, config, timestamp=None,
269
timezone=None, committer=None, revprops=None,
271
"""Obtain a CommitBuilder for this repository.
273
:param branch: Branch to commit to.
274
:param parents: Revision ids of the parents of the new revision.
275
:param config: Configuration to use.
276
:param timestamp: Optional timestamp recorded for commit.
277
:param timezone: Optional timezone for timestamp.
278
:param committer: Optional committer to set for commit.
279
:param revprops: Optional dictionary of revision properties.
280
:param revision_id: Optional revision id.
282
return _CommitBuilder(self, parents, config, timestamp, timezone,
283
committer, revprops, revision_id)
286
self.control_files.unlock()
289
def clone(self, a_bzrdir, revision_id=None, basis=None):
290
"""Clone this repository into a_bzrdir using the current format.
292
Currently no check is made that the format of this repository and
293
the bzrdir format are compatible. FIXME RBC 20060201.
295
:return: The newly created destination repository.
297
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
298
# use target default format.
299
dest_repo = a_bzrdir.create_repository()
301
# Most control formats need the repository to be specifically
302
# created, but on some old all-in-one formats it's not needed
304
dest_repo = self._format.initialize(a_bzrdir, shared=self.is_shared())
305
except errors.UninitializableFormat:
306
dest_repo = a_bzrdir.open_repository()
307
self.copy_content_into(dest_repo, revision_id, basis)
311
def has_revision(self, revision_id):
312
"""True if this repository has a copy of the revision."""
313
return self._revision_store.has_revision_id(revision_id,
314
self.get_transaction())
317
def get_revision_reconcile(self, revision_id):
318
"""'reconcile' helper routine that allows access to a revision always.
320
This variant of get_revision does not cross check the weave graph
321
against the revision one as get_revision does: but it should only
322
be used by reconcile, or reconcile-alike commands that are correcting
323
or testing the revision graph.
325
if not revision_id or not isinstance(revision_id, basestring):
326
raise errors.InvalidRevisionId(revision_id=revision_id,
328
return self._revision_store.get_revisions([revision_id],
329
self.get_transaction())[0]
331
def get_revisions(self, revision_ids):
332
return self._revision_store.get_revisions(revision_ids,
333
self.get_transaction())
336
def get_revision_xml(self, revision_id):
337
rev = self.get_revision(revision_id)
339
# the current serializer..
340
self._revision_store._serializer.write_revision(rev, rev_tmp)
342
return rev_tmp.getvalue()
345
def get_revision(self, revision_id):
346
"""Return the Revision object for a named revision"""
347
r = self.get_revision_reconcile(revision_id)
348
# weave corruption can lead to absent revision markers that should be
350
# the following test is reasonably cheap (it needs a single weave read)
351
# and the weave is cached in read transactions. In write transactions
352
# it is not cached but typically we only read a small number of
353
# revisions. For knits when they are introduced we will probably want
354
# to ensure that caching write transactions are in use.
355
inv = self.get_inventory_weave()
356
self._check_revision_parents(r, inv)
360
def get_deltas_for_revisions(self, revisions):
361
"""Produce a generator of revision deltas.
363
Note that the input is a sequence of REVISIONS, not revision_ids.
364
Trees will be held in memory until the generator exits.
365
Each delta is relative to the revision's lefthand predecessor.
367
required_trees = set()
368
for revision in revisions:
369
required_trees.add(revision.revision_id)
370
required_trees.update(revision.parent_ids[:1])
371
trees = dict((t.get_revision_id(), t) for
372
t in self.revision_trees(required_trees))
373
for revision in revisions:
374
if not revision.parent_ids:
375
old_tree = self.revision_tree(None)
377
old_tree = trees[revision.parent_ids[0]]
378
yield trees[revision.revision_id].changes_from(old_tree)
381
def get_revision_delta(self, revision_id):
382
"""Return the delta for one revision.
384
The delta is relative to the left-hand predecessor of the
387
r = self.get_revision(revision_id)
388
return list(self.get_deltas_for_revisions([r]))[0]
390
def _check_revision_parents(self, revision, inventory):
391
"""Private to Repository and Fetch.
393
This checks the parentage of revision in an inventory weave for
394
consistency and is only applicable to inventory-weave-for-ancestry
395
using repository formats & fetchers.
397
weave_parents = inventory.get_parents(revision.revision_id)
398
weave_names = inventory.versions()
399
for parent_id in revision.parent_ids:
400
if parent_id in weave_names:
401
# this parent must not be a ghost.
402
if not parent_id in weave_parents:
404
raise errors.CorruptRepository(self)
407
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
408
signature = gpg_strategy.sign(plaintext)
409
self._revision_store.add_revision_signature_text(revision_id,
411
self.get_transaction())
413
def fileids_altered_by_revision_ids(self, revision_ids):
414
"""Find the file ids and versions affected by revisions.
416
:param revisions: an iterable containing revision ids.
417
:return: a dictionary mapping altered file-ids to an iterable of
418
revision_ids. Each altered file-ids has the exact revision_ids that
419
altered it listed explicitly.
421
assert self._serializer.support_altered_by_hack, \
422
("fileids_altered_by_revision_ids only supported for branches "
423
"which store inventory as unnested xml, not on %r" % self)
424
selected_revision_ids = set(revision_ids)
425
w = self.get_inventory_weave()
428
# this code needs to read every new line in every inventory for the
429
# inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
430
# not present in one of those inventories is unnecessary but not
431
# harmful because we are filtering by the revision id marker in the
432
# inventory lines : we only select file ids altered in one of those
433
# revisions. We don't need to see all lines in the inventory because
434
# only those added in an inventory in rev X can contain a revision=X
436
unescape_revid_cache = {}
437
unescape_fileid_cache = {}
439
# jam 20061218 In a big fetch, this handles hundreds of thousands
440
# of lines, so it has had a lot of inlining and optimizing done.
441
# Sorry that it is a little bit messy.
442
# Move several functions to be local variables, since this is a long
444
search = self._file_ids_altered_regex.search
445
unescape = _unescape_xml
446
setdefault = result.setdefault
447
pb = ui.ui_factory.nested_progress_bar()
449
for line in w.iter_lines_added_or_present_in_versions(
450
selected_revision_ids, pb=pb):
454
# One call to match.group() returning multiple items is quite a
455
# bit faster than 2 calls to match.group() each returning 1
456
file_id, revision_id = match.group('file_id', 'revision_id')
458
# Inlining the cache lookups helps a lot when you make 170,000
459
# lines and 350k ids, versus 8.4 unique ids.
460
# Using a cache helps in 2 ways:
461
# 1) Avoids unnecessary decoding calls
462
# 2) Re-uses cached strings, which helps in future set and
464
# (2) is enough that removing encoding entirely along with
465
# the cache (so we are using plain strings) results in no
466
# performance improvement.
468
revision_id = unescape_revid_cache[revision_id]
470
unescaped = unescape(revision_id)
471
unescape_revid_cache[revision_id] = unescaped
472
revision_id = unescaped
474
if revision_id in selected_revision_ids:
476
file_id = unescape_fileid_cache[file_id]
478
unescaped = unescape(file_id)
479
unescape_fileid_cache[file_id] = unescaped
481
setdefault(file_id, set()).add(revision_id)
487
def get_inventory_weave(self):
488
return self.control_weaves.get_weave('inventory',
489
self.get_transaction())
492
def get_inventory(self, revision_id):
493
"""Get Inventory object by hash."""
494
return self.deserialise_inventory(
495
revision_id, self.get_inventory_xml(revision_id))
497
def deserialise_inventory(self, revision_id, xml):
498
"""Transform the xml into an inventory object.
500
:param revision_id: The expected revision id of the inventory.
501
:param xml: A serialised inventory.
503
result = self._serializer.read_inventory_from_string(xml)
504
result.root.revision = revision_id
507
def serialise_inventory(self, inv):
508
return self._serializer.write_inventory_to_string(inv)
511
def get_inventory_xml(self, revision_id):
512
"""Get inventory XML as a file object."""
514
assert isinstance(revision_id, basestring), type(revision_id)
515
iw = self.get_inventory_weave()
516
return iw.get_text(revision_id)
518
raise errors.HistoryMissing(self, 'inventory', revision_id)
521
def get_inventory_sha1(self, revision_id):
522
"""Return the sha1 hash of the inventory entry
524
return self.get_revision(revision_id).inventory_sha1
527
def get_revision_graph(self, revision_id=None):
528
"""Return a dictionary containing the revision graph.
530
:param revision_id: The revision_id to get a graph from. If None, then
531
the entire revision graph is returned. This is a deprecated mode of
532
operation and will be removed in the future.
533
:return: a dictionary of revision_id->revision_parents_list.
535
# special case NULL_REVISION
536
if revision_id == _mod_revision.NULL_REVISION:
538
a_weave = self.get_inventory_weave()
539
all_revisions = self._eliminate_revisions_not_present(
541
entire_graph = dict([(node, a_weave.get_parents(node)) for
542
node in all_revisions])
543
if revision_id is None:
545
elif revision_id not in entire_graph:
546
raise errors.NoSuchRevision(self, revision_id)
548
# add what can be reached from revision_id
550
pending = set([revision_id])
551
while len(pending) > 0:
553
result[node] = entire_graph[node]
554
for revision_id in result[node]:
555
if revision_id not in result:
556
pending.add(revision_id)
560
def get_revision_graph_with_ghosts(self, revision_ids=None):
561
"""Return a graph of the revisions with ghosts marked as applicable.
563
:param revision_ids: an iterable of revisions to graph or None for all.
564
:return: a Graph object with the graph reachable from revision_ids.
566
result = graph.Graph()
568
pending = set(self.all_revision_ids())
571
pending = set(revision_ids)
572
# special case NULL_REVISION
573
if _mod_revision.NULL_REVISION in pending:
574
pending.remove(_mod_revision.NULL_REVISION)
575
required = set(pending)
578
revision_id = pending.pop()
580
rev = self.get_revision(revision_id)
581
except errors.NoSuchRevision:
582
if revision_id in required:
585
result.add_ghost(revision_id)
587
for parent_id in rev.parent_ids:
588
# is this queued or done ?
589
if (parent_id not in pending and
590
parent_id not in done):
592
pending.add(parent_id)
593
result.add_node(revision_id, rev.parent_ids)
594
done.add(revision_id)
598
def get_revision_inventory(self, revision_id):
599
"""Return inventory of a past revision."""
600
# TODO: Unify this with get_inventory()
601
# bzr 0.0.6 and later imposes the constraint that the inventory_id
602
# must be the same as its revision, so this is trivial.
603
if revision_id is None:
604
# This does not make sense: if there is no revision,
605
# then it is the current tree inventory surely ?!
606
# and thus get_root_id() is something that looks at the last
607
# commit on the branch, and the get_root_id is an inventory check.
608
raise NotImplementedError
609
# return Inventory(self.get_root_id())
611
return self.get_inventory(revision_id)
615
"""Return True if this repository is flagged as a shared repository."""
616
raise NotImplementedError(self.is_shared)
619
def reconcile(self, other=None, thorough=False):
620
"""Reconcile this repository."""
621
from bzrlib.reconcile import RepoReconciler
622
reconciler = RepoReconciler(self, thorough=thorough)
623
reconciler.reconcile()
627
def revision_tree(self, revision_id):
628
"""Return Tree for a revision on this branch.
630
`revision_id` may be None for the empty tree revision.
632
# TODO: refactor this to use an existing revision object
633
# so we don't need to read it in twice.
634
if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
635
return RevisionTree(self, Inventory(root_id=None),
636
_mod_revision.NULL_REVISION)
638
inv = self.get_revision_inventory(revision_id)
639
return RevisionTree(self, inv, revision_id)
642
def revision_trees(self, revision_ids):
643
"""Return Tree for a revision on this branch.
645
`revision_id` may not be None or 'null:'"""
646
assert None not in revision_ids
647
assert _mod_revision.NULL_REVISION not in revision_ids
648
texts = self.get_inventory_weave().get_texts(revision_ids)
649
for text, revision_id in zip(texts, revision_ids):
650
inv = self.deserialise_inventory(revision_id, text)
651
yield RevisionTree(self, inv, revision_id)
654
def get_ancestry(self, revision_id):
655
"""Return a list of revision-ids integrated by a revision.
657
The first element of the list is always None, indicating the origin
658
revision. This might change when we have history horizons, or
659
perhaps we should have a new API.
661
This is topologically sorted.
663
if revision_id is None:
665
if not self.has_revision(revision_id):
666
raise errors.NoSuchRevision(self, revision_id)
667
w = self.get_inventory_weave()
668
candidates = w.get_ancestry(revision_id)
669
return [None] + candidates # self._eliminate_revisions_not_present(candidates)
672
def print_file(self, file, revision_id):
673
"""Print `file` to stdout.
675
FIXME RBC 20060125 as John Meinel points out this is a bad api
676
- it writes to stdout, it assumes that that is valid etc. Fix
677
by creating a new more flexible convenience function.
679
tree = self.revision_tree(revision_id)
680
# use inventory as it was in that revision
681
file_id = tree.inventory.path2id(file)
683
# TODO: jam 20060427 Write a test for this code path
684
# it had a bug in it, and was raising the wrong
686
raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
687
tree.print_file(file_id)
689
def get_transaction(self):
690
return self.control_files.get_transaction()
692
def revision_parents(self, revid):
693
return self.get_inventory_weave().parent_names(revid)
696
def set_make_working_trees(self, new_value):
697
"""Set the policy flag for making working trees when creating branches.
699
This only applies to branches that use this repository.
701
The default is 'True'.
702
:param new_value: True to restore the default, False to disable making
705
raise NotImplementedError(self.set_make_working_trees)
707
def make_working_trees(self):
708
"""Returns the policy for making working trees on new branches."""
709
raise NotImplementedError(self.make_working_trees)
712
def sign_revision(self, revision_id, gpg_strategy):
713
plaintext = Testament.from_revision(self, revision_id).as_short_text()
714
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
717
def has_signature_for_revision_id(self, revision_id):
718
"""Query for a revision signature for revision_id in the repository."""
719
return self._revision_store.has_signature(revision_id,
720
self.get_transaction())
723
def get_signature_text(self, revision_id):
724
"""Return the text for a signature."""
725
return self._revision_store.get_signature_text(revision_id,
726
self.get_transaction())
729
def check(self, revision_ids):
730
"""Check consistency of all history of given revision_ids.
732
Different repository implementations should override _check().
734
:param revision_ids: A non-empty list of revision_ids whose ancestry
735
will be checked. Typically the last revision_id of a branch.
738
raise ValueError("revision_ids must be non-empty in %s.check"
740
return self._check(revision_ids)
742
def _check(self, revision_ids):
743
result = check.Check(self)
747
def _warn_if_deprecated(self):
748
global _deprecation_warning_done
749
if _deprecation_warning_done:
751
_deprecation_warning_done = True
752
warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
753
% (self._format, self.bzrdir.transport.base))
755
def supports_rich_root(self):
756
return self._format.rich_root_data
758
def _check_ascii_revisionid(self, revision_id, method):
759
"""Private helper for ascii-only repositories."""
760
# weave repositories refuse to store revisionids that are non-ascii.
761
if revision_id is not None:
762
# weaves require ascii revision ids.
763
if isinstance(revision_id, unicode):
765
revision_id.encode('ascii')
766
except UnicodeEncodeError:
767
raise errors.NonAsciiRevisionId(method, self)
771
# remove these delegates a while after bzr 0.15
772
def __make_delegated(name, from_module):
773
def _deprecated_repository_forwarder():
774
symbol_versioning.warn('%s moved to %s in bzr 0.15'
775
% (name, from_module),
777
m = __import__(from_module, globals(), locals(), [name])
779
return getattr(m, name)
780
except AttributeError:
781
raise AttributeError('module %s has no name %s'
783
globals()[name] = _deprecated_repository_forwarder
786
'AllInOneRepository',
787
'WeaveMetaDirRepository',
788
'PreSplitOutRepositoryFormat',
794
__make_delegated(_name, 'bzrlib.repofmt.weaverepo')
799
'RepositoryFormatKnit',
800
'RepositoryFormatKnit1',
801
'RepositoryFormatKnit2',
803
__make_delegated(_name, 'bzrlib.repofmt.knitrepo')
806
def install_revision(repository, rev, revision_tree):
807
"""Install all revision data into a repository."""
810
for p_id in rev.parent_ids:
811
if repository.has_revision(p_id):
812
present_parents.append(p_id)
813
parent_trees[p_id] = repository.revision_tree(p_id)
815
parent_trees[p_id] = repository.revision_tree(None)
817
inv = revision_tree.inventory
818
entries = inv.iter_entries()
819
# backwards compatability hack: skip the root id.
820
if not repository.supports_rich_root():
821
path, root = entries.next()
822
if root.revision != rev.revision_id:
823
raise errors.IncompatibleRevision(repr(repository))
824
# Add the texts that are not already present
825
for path, ie in entries:
826
w = repository.weave_store.get_weave_or_empty(ie.file_id,
827
repository.get_transaction())
828
if ie.revision not in w:
830
# FIXME: TODO: The following loop *may* be overlapping/duplicate
831
# with InventoryEntry.find_previous_heads(). if it is, then there
832
# is a latent bug here where the parents may have ancestors of each
834
for revision, tree in parent_trees.iteritems():
835
if ie.file_id not in tree:
837
parent_id = tree.inventory[ie.file_id].revision
838
if parent_id in text_parents:
840
text_parents.append(parent_id)
842
vfile = repository.weave_store.get_weave_or_empty(ie.file_id,
843
repository.get_transaction())
844
lines = revision_tree.get_file(ie.file_id).readlines()
845
vfile.add_lines(rev.revision_id, text_parents, lines)
847
# install the inventory
848
repository.add_inventory(rev.revision_id, inv, present_parents)
849
except errors.RevisionAlreadyPresent:
851
repository.add_revision(rev.revision_id, rev, inv)
854
class MetaDirRepository(Repository):
855
"""Repositories in the new meta-dir layout."""
857
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
858
super(MetaDirRepository, self).__init__(_format,
864
dir_mode = self.control_files._dir_mode
865
file_mode = self.control_files._file_mode
869
"""Return True if this repository is flagged as a shared repository."""
870
return self.control_files._transport.has('shared-storage')
873
def set_make_working_trees(self, new_value):
874
"""Set the policy flag for making working trees when creating branches.
876
This only applies to branches that use this repository.
878
The default is 'True'.
879
:param new_value: True to restore the default, False to disable making
884
self.control_files._transport.delete('no-working-trees')
885
except errors.NoSuchFile:
888
self.control_files.put_utf8('no-working-trees', '')
890
def make_working_trees(self):
891
"""Returns the policy for making working trees on new branches."""
892
return not self.control_files._transport.has('no-working-trees')
895
class RepositoryFormatRegistry(registry.Registry):
896
"""Registry of RepositoryFormats.
899
def get(self, format_string):
900
r = registry.Registry.get(self, format_string)
906
format_registry = RepositoryFormatRegistry()
907
"""Registry of formats, indexed by their identifying format string.
909
This can contain either format instances themselves, or classes/factories that
910
can be called to obtain one.
914
class RepositoryFormat(object):
915
"""A repository format.
917
Formats provide three things:
918
* An initialization routine to construct repository data on disk.
919
* a format string which is used when the BzrDir supports versioned
921
* an open routine which returns a Repository instance.
923
Formats are placed in an dict by their format string for reference
924
during opening. These should be subclasses of RepositoryFormat
927
Once a format is deprecated, just deprecate the initialize and open
928
methods on the format class. Do not deprecate the object, as the
929
object will be created every system load.
931
Common instance attributes:
932
_matchingbzrdir - the bzrdir format that the repository format was
933
originally written to work with. This can be used if manually
934
constructing a bzrdir and repository, or more commonly for test suite
939
return "<%s>" % self.__class__.__name__
941
def __eq__(self, other):
942
# format objects are generally stateless
943
return isinstance(other, self.__class__)
946
def find_format(klass, a_bzrdir):
947
"""Return the format for the repository object in a_bzrdir.
949
This is used by bzr native formats that have a "format" file in
950
the repository. Other methods may be used by different types of
954
transport = a_bzrdir.get_repository_transport(None)
955
format_string = transport.get("format").read()
956
return format_registry.get(format_string)
957
except errors.NoSuchFile:
958
raise errors.NoRepositoryPresent(a_bzrdir)
960
raise errors.UnknownFormatError(format=format_string)
963
@deprecated_method(symbol_versioning.zero_fourteen)
964
def set_default_format(klass, format):
965
klass._set_default_format(format)
968
def _set_default_format(klass, format):
969
"""Set the default format for new Repository creation.
971
The format must already be registered.
973
format_registry.default_key = format.get_format_string()
976
def register_format(klass, format):
977
format_registry.register(format.get_format_string(), format)
980
def unregister_format(klass, format):
981
format_registry.remove(format.get_format_string())
984
def get_default_format(klass):
985
"""Return the current default format."""
986
return format_registry.get(format_registry.default_key)
988
def _get_control_store(self, repo_transport, control_files):
989
"""Return the control store for this repository."""
990
raise NotImplementedError(self._get_control_store)
992
def get_format_string(self):
993
"""Return the ASCII format string that identifies this format.
995
Note that in pre format ?? repositories the format string is
996
not permitted nor written to disk.
998
raise NotImplementedError(self.get_format_string)
1000
def get_format_description(self):
1001
"""Return the short description for this format."""
1002
raise NotImplementedError(self.get_format_description)
1004
def _get_revision_store(self, repo_transport, control_files):
1005
"""Return the revision store object for this a_bzrdir."""
1006
raise NotImplementedError(self._get_revision_store)
1008
def _get_text_rev_store(self,
1015
"""Common logic for getting a revision store for a repository.
1017
see self._get_revision_store for the subclass-overridable method to
1018
get the store for a repository.
1020
from bzrlib.store.revision.text import TextRevisionStore
1021
dir_mode = control_files._dir_mode
1022
file_mode = control_files._file_mode
1023
text_store =TextStore(transport.clone(name),
1025
compressed=compressed,
1027
file_mode=file_mode)
1028
_revision_store = TextRevisionStore(text_store, serializer)
1029
return _revision_store
1031
# TODO: this shouldn't be in the base class, it's specific to things that
1032
# use weaves or knits -- mbp 20070207
1033
def _get_versioned_file_store(self,
1038
versionedfile_class=None,
1039
versionedfile_kwargs={},
1041
if versionedfile_class is None:
1042
versionedfile_class = self._versionedfile_class
1043
weave_transport = control_files._transport.clone(name)
1044
dir_mode = control_files._dir_mode
1045
file_mode = control_files._file_mode
1046
return VersionedFileStore(weave_transport, prefixed=prefixed,
1048
file_mode=file_mode,
1049
versionedfile_class=versionedfile_class,
1050
versionedfile_kwargs=versionedfile_kwargs,
1053
def initialize(self, a_bzrdir, shared=False):
1054
"""Initialize a repository of this format in a_bzrdir.
1056
:param a_bzrdir: The bzrdir to put the new repository in it.
1057
:param shared: The repository should be initialized as a sharable one.
1059
This may raise UninitializableFormat if shared repository are not
1060
compatible the a_bzrdir.
1063
def is_supported(self):
1064
"""Is this format supported?
1066
Supported formats must be initializable and openable.
1067
Unsupported formats may not support initialization or committing or
1068
some other features depending on the reason for not being supported.
1072
def check_conversion_target(self, target_format):
1073
raise NotImplementedError(self.check_conversion_target)
1075
def open(self, a_bzrdir, _found=False):
1076
"""Return an instance of this format for the bzrdir a_bzrdir.
1078
_found is a private parameter, do not use it.
1080
raise NotImplementedError(self.open)
1083
class MetaDirRepositoryFormat(RepositoryFormat):
1084
"""Common base class for the new repositories using the metadir layout."""
1086
rich_root_data = False
1087
_matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1090
super(MetaDirRepositoryFormat, self).__init__()
1092
def _create_control_files(self, a_bzrdir):
1093
"""Create the required files and the initial control_files object."""
1094
# FIXME: RBC 20060125 don't peek under the covers
1095
# NB: no need to escape relative paths that are url safe.
1096
repository_transport = a_bzrdir.get_repository_transport(self)
1097
control_files = lockable_files.LockableFiles(repository_transport,
1098
'lock', lockdir.LockDir)
1099
control_files.create_lock()
1100
return control_files
1102
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1103
"""Upload the initial blank content."""
1104
control_files = self._create_control_files(a_bzrdir)
1105
control_files.lock_write()
1107
control_files._transport.mkdir_multi(dirs,
1108
mode=control_files._dir_mode)
1109
for file, content in files:
1110
control_files.put(file, content)
1111
for file, content in utf8_files:
1112
control_files.put_utf8(file, content)
1114
control_files.put_utf8('shared-storage', '')
1116
control_files.unlock()
1119
# formats which have no format string are not discoverable
1120
# and not independently creatable, so are not registered. They're
1121
# all in bzrlib.repofmt.weaverepo now. When an instance of one of these is
1122
# needed, it's constructed directly by the BzrDir. Non-native formats where
1123
# the repository is not separately opened are similar.
1125
format_registry.register_lazy(
1126
'Bazaar-NG Repository format 7',
1127
'bzrlib.repofmt.weaverepo',
1130
# KEEP in sync with bzrdir.format_registry default, which controls the overall
1131
# default control directory format
1133
format_registry.register_lazy(
1134
'Bazaar-NG Knit Repository Format 1',
1135
'bzrlib.repofmt.knitrepo',
1136
'RepositoryFormatKnit1',
1138
format_registry.default_key = 'Bazaar-NG Knit Repository Format 1'
1140
format_registry.register_lazy(
1141
'Bazaar Knit Repository Format 2\n',
1142
'bzrlib.repofmt.knitrepo',
1143
'RepositoryFormatKnit2',
1147
class InterRepository(InterObject):
1148
"""This class represents operations taking place between two repositories.
1150
Its instances have methods like copy_content and fetch, and contain
1151
references to the source and target repositories these operations can be
1154
Often we will provide convenience methods on 'repository' which carry out
1155
operations with another repository - they will always forward to
1156
InterRepository.get(other).method_name(parameters).
1160
"""The available optimised InterRepository types."""
1162
def copy_content(self, revision_id=None, basis=None):
1163
raise NotImplementedError(self.copy_content)
1165
def fetch(self, revision_id=None, pb=None):
1166
"""Fetch the content required to construct revision_id.
1168
The content is copied from self.source to self.target.
1170
:param revision_id: if None all content is copied, if NULL_REVISION no
1172
:param pb: optional progress bar to use for progress reports. If not
1173
provided a default one will be created.
1175
Returns the copied revision count and the failed revisions in a tuple:
1178
raise NotImplementedError(self.fetch)
1181
def missing_revision_ids(self, revision_id=None):
1182
"""Return the revision ids that source has that target does not.
1184
These are returned in topological order.
1186
:param revision_id: only return revision ids included by this
1189
# generic, possibly worst case, slow code path.
1190
target_ids = set(self.target.all_revision_ids())
1191
if revision_id is not None:
1192
source_ids = self.source.get_ancestry(revision_id)
1193
assert source_ids[0] is None
1196
source_ids = self.source.all_revision_ids()
1197
result_set = set(source_ids).difference(target_ids)
1198
# this may look like a no-op: its not. It preserves the ordering
1199
# other_ids had while only returning the members from other_ids
1200
# that we've decided we need.
1201
return [rev_id for rev_id in source_ids if rev_id in result_set]
1204
class InterSameDataRepository(InterRepository):
1205
"""Code for converting between repositories that represent the same data.
1207
Data format and model must match for this to work.
1211
def _get_repo_format_to_test(self):
1212
"""Repository format for testing with."""
1213
return RepositoryFormat.get_default_format()
1216
def is_compatible(source, target):
1217
if not isinstance(source, Repository):
1219
if not isinstance(target, Repository):
1221
if source._format.rich_root_data == target._format.rich_root_data:
1227
def copy_content(self, revision_id=None, basis=None):
1228
"""Make a complete copy of the content in self into destination.
1230
This is a destructive operation! Do not use it on existing
1233
:param revision_id: Only copy the content needed to construct
1234
revision_id and its parents.
1235
:param basis: Copy the needed data preferentially from basis.
1238
self.target.set_make_working_trees(self.source.make_working_trees())
1239
except NotImplementedError:
1241
# grab the basis available data
1242
if basis is not None:
1243
self.target.fetch(basis, revision_id=revision_id)
1244
# but don't bother fetching if we have the needed data now.
1245
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1246
self.target.has_revision(revision_id)):
1248
self.target.fetch(self.source, revision_id=revision_id)
1251
def fetch(self, revision_id=None, pb=None):
1252
"""See InterRepository.fetch()."""
1253
from bzrlib.fetch import GenericRepoFetcher
1254
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1255
self.source, self.source._format, self.target,
1256
self.target._format)
1257
f = GenericRepoFetcher(to_repository=self.target,
1258
from_repository=self.source,
1259
last_revision=revision_id,
1261
return f.count_copied, f.failed_revisions
1264
class InterWeaveRepo(InterSameDataRepository):
1265
"""Optimised code paths between Weave based repositories."""
1268
def _get_repo_format_to_test(self):
1269
from bzrlib.repofmt import weaverepo
1270
return weaverepo.RepositoryFormat7()
1273
def is_compatible(source, target):
1274
"""Be compatible with known Weave formats.
1276
We don't test for the stores being of specific types because that
1277
could lead to confusing results, and there is no need to be
1280
from bzrlib.repofmt.weaverepo import (
1286
return (isinstance(source._format, (RepositoryFormat5,
1288
RepositoryFormat7)) and
1289
isinstance(target._format, (RepositoryFormat5,
1291
RepositoryFormat7)))
1292
except AttributeError:
1296
def copy_content(self, revision_id=None, basis=None):
1297
"""See InterRepository.copy_content()."""
1298
# weave specific optimised path:
1299
if basis is not None:
1300
# copy the basis in, then fetch remaining data.
1301
basis.copy_content_into(self.target, revision_id)
1302
# the basis copy_content_into could miss-set this.
1304
self.target.set_make_working_trees(self.source.make_working_trees())
1305
except NotImplementedError:
1307
self.target.fetch(self.source, revision_id=revision_id)
1310
self.target.set_make_working_trees(self.source.make_working_trees())
1311
except NotImplementedError:
1313
# FIXME do not peek!
1314
if self.source.control_files._transport.listable():
1315
pb = ui.ui_factory.nested_progress_bar()
1317
self.target.weave_store.copy_all_ids(
1318
self.source.weave_store,
1320
from_transaction=self.source.get_transaction(),
1321
to_transaction=self.target.get_transaction())
1322
pb.update('copying inventory', 0, 1)
1323
self.target.control_weaves.copy_multi(
1324
self.source.control_weaves, ['inventory'],
1325
from_transaction=self.source.get_transaction(),
1326
to_transaction=self.target.get_transaction())
1327
self.target._revision_store.text_store.copy_all_ids(
1328
self.source._revision_store.text_store,
1333
self.target.fetch(self.source, revision_id=revision_id)
1336
def fetch(self, revision_id=None, pb=None):
1337
"""See InterRepository.fetch()."""
1338
from bzrlib.fetch import GenericRepoFetcher
1339
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1340
self.source, self.source._format, self.target, self.target._format)
1341
f = GenericRepoFetcher(to_repository=self.target,
1342
from_repository=self.source,
1343
last_revision=revision_id,
1345
return f.count_copied, f.failed_revisions
1348
def missing_revision_ids(self, revision_id=None):
1349
"""See InterRepository.missing_revision_ids()."""
1350
# we want all revisions to satisfy revision_id in source.
1351
# but we don't want to stat every file here and there.
1352
# we want then, all revisions other needs to satisfy revision_id
1353
# checked, but not those that we have locally.
1354
# so the first thing is to get a subset of the revisions to
1355
# satisfy revision_id in source, and then eliminate those that
1356
# we do already have.
1357
# this is slow on high latency connection to self, but as as this
1358
# disk format scales terribly for push anyway due to rewriting
1359
# inventory.weave, this is considered acceptable.
1361
if revision_id is not None:
1362
source_ids = self.source.get_ancestry(revision_id)
1363
assert source_ids[0] is None
1366
source_ids = self.source._all_possible_ids()
1367
source_ids_set = set(source_ids)
1368
# source_ids is the worst possible case we may need to pull.
1369
# now we want to filter source_ids against what we actually
1370
# have in target, but don't try to check for existence where we know
1371
# we do not have a revision as that would be pointless.
1372
target_ids = set(self.target._all_possible_ids())
1373
possibly_present_revisions = target_ids.intersection(source_ids_set)
1374
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1375
required_revisions = source_ids_set.difference(actually_present_revisions)
1376
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1377
if revision_id is not None:
1378
# we used get_ancestry to determine source_ids then we are assured all
1379
# revisions referenced are present as they are installed in topological order.
1380
# and the tip revision was validated by get_ancestry.
1381
return required_topo_revisions
1383
# if we just grabbed the possibly available ids, then
1384
# we only have an estimate of whats available and need to validate
1385
# that against the revision records.
1386
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1389
class InterKnitRepo(InterSameDataRepository):
1390
"""Optimised code paths between Knit based repositories."""
1393
def _get_repo_format_to_test(self):
1394
from bzrlib.repofmt import knitrepo
1395
return knitrepo.RepositoryFormatKnit1()
1398
def is_compatible(source, target):
1399
"""Be compatible with known Knit formats.
1401
We don't test for the stores being of specific types because that
1402
could lead to confusing results, and there is no need to be
1405
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1
1407
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1408
isinstance(target._format, (RepositoryFormatKnit1)))
1409
except AttributeError:
1413
def fetch(self, revision_id=None, pb=None):
1414
"""See InterRepository.fetch()."""
1415
from bzrlib.fetch import KnitRepoFetcher
1416
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1417
self.source, self.source._format, self.target, self.target._format)
1418
f = KnitRepoFetcher(to_repository=self.target,
1419
from_repository=self.source,
1420
last_revision=revision_id,
1422
return f.count_copied, f.failed_revisions
1425
def missing_revision_ids(self, revision_id=None):
1426
"""See InterRepository.missing_revision_ids()."""
1427
if revision_id is not None:
1428
source_ids = self.source.get_ancestry(revision_id)
1429
assert source_ids[0] is None
1432
source_ids = self.source._all_possible_ids()
1433
source_ids_set = set(source_ids)
1434
# source_ids is the worst possible case we may need to pull.
1435
# now we want to filter source_ids against what we actually
1436
# have in target, but don't try to check for existence where we know
1437
# we do not have a revision as that would be pointless.
1438
target_ids = set(self.target._all_possible_ids())
1439
possibly_present_revisions = target_ids.intersection(source_ids_set)
1440
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1441
required_revisions = source_ids_set.difference(actually_present_revisions)
1442
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1443
if revision_id is not None:
1444
# we used get_ancestry to determine source_ids then we are assured all
1445
# revisions referenced are present as they are installed in topological order.
1446
# and the tip revision was validated by get_ancestry.
1447
return required_topo_revisions
1449
# if we just grabbed the possibly available ids, then
1450
# we only have an estimate of whats available and need to validate
1451
# that against the revision records.
1452
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1455
class InterModel1and2(InterRepository):
1458
def _get_repo_format_to_test(self):
1462
def is_compatible(source, target):
1463
if not isinstance(source, Repository):
1465
if not isinstance(target, Repository):
1467
if not source._format.rich_root_data and target._format.rich_root_data:
1473
def fetch(self, revision_id=None, pb=None):
1474
"""See InterRepository.fetch()."""
1475
from bzrlib.fetch import Model1toKnit2Fetcher
1476
f = Model1toKnit2Fetcher(to_repository=self.target,
1477
from_repository=self.source,
1478
last_revision=revision_id,
1480
return f.count_copied, f.failed_revisions
1483
def copy_content(self, revision_id=None, basis=None):
1484
"""Make a complete copy of the content in self into destination.
1486
This is a destructive operation! Do not use it on existing
1489
:param revision_id: Only copy the content needed to construct
1490
revision_id and its parents.
1491
:param basis: Copy the needed data preferentially from basis.
1494
self.target.set_make_working_trees(self.source.make_working_trees())
1495
except NotImplementedError:
1497
# grab the basis available data
1498
if basis is not None:
1499
self.target.fetch(basis, revision_id=revision_id)
1500
# but don't bother fetching if we have the needed data now.
1501
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1502
self.target.has_revision(revision_id)):
1504
self.target.fetch(self.source, revision_id=revision_id)
1507
class InterKnit1and2(InterKnitRepo):
1510
def _get_repo_format_to_test(self):
1514
def is_compatible(source, target):
1515
"""Be compatible with Knit1 source and Knit2 target"""
1516
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit2
1518
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1, \
1519
RepositoryFormatKnit2
1520
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1521
isinstance(target._format, (RepositoryFormatKnit2)))
1522
except AttributeError:
1526
def fetch(self, revision_id=None, pb=None):
1527
"""See InterRepository.fetch()."""
1528
from bzrlib.fetch import Knit1to2Fetcher
1529
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1530
self.source, self.source._format, self.target,
1531
self.target._format)
1532
f = Knit1to2Fetcher(to_repository=self.target,
1533
from_repository=self.source,
1534
last_revision=revision_id,
1536
return f.count_copied, f.failed_revisions
1539
InterRepository.register_optimiser(InterSameDataRepository)
1540
InterRepository.register_optimiser(InterWeaveRepo)
1541
InterRepository.register_optimiser(InterKnitRepo)
1542
InterRepository.register_optimiser(InterModel1and2)
1543
InterRepository.register_optimiser(InterKnit1and2)
1546
class RepositoryTestProviderAdapter(object):
1547
"""A tool to generate a suite testing multiple repository formats at once.
1549
This is done by copying the test once for each transport and injecting
1550
the transport_server, transport_readonly_server, and bzrdir_format and
1551
repository_format classes into each copy. Each copy is also given a new id()
1552
to make it easy to identify.
1555
def __init__(self, transport_server, transport_readonly_server, formats):
1556
self._transport_server = transport_server
1557
self._transport_readonly_server = transport_readonly_server
1558
self._formats = formats
1560
def adapt(self, test):
1561
result = unittest.TestSuite()
1562
for repository_format, bzrdir_format in self._formats:
1563
from copy import deepcopy
1564
new_test = deepcopy(test)
1565
new_test.transport_server = self._transport_server
1566
new_test.transport_readonly_server = self._transport_readonly_server
1567
new_test.bzrdir_format = bzrdir_format
1568
new_test.repository_format = repository_format
1569
def make_new_test_id():
1570
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1571
return lambda: new_id
1572
new_test.id = make_new_test_id()
1573
result.addTest(new_test)
1577
class InterRepositoryTestProviderAdapter(object):
1578
"""A tool to generate a suite testing multiple inter repository formats.
1580
This is done by copying the test once for each interrepo provider and injecting
1581
the transport_server, transport_readonly_server, repository_format and
1582
repository_to_format classes into each copy.
1583
Each copy is also given a new id() to make it easy to identify.
1586
def __init__(self, transport_server, transport_readonly_server, formats):
1587
self._transport_server = transport_server
1588
self._transport_readonly_server = transport_readonly_server
1589
self._formats = formats
1591
def adapt(self, test):
1592
result = unittest.TestSuite()
1593
for interrepo_class, repository_format, repository_format_to in self._formats:
1594
from copy import deepcopy
1595
new_test = deepcopy(test)
1596
new_test.transport_server = self._transport_server
1597
new_test.transport_readonly_server = self._transport_readonly_server
1598
new_test.interrepo_class = interrepo_class
1599
new_test.repository_format = repository_format
1600
new_test.repository_format_to = repository_format_to
1601
def make_new_test_id():
1602
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1603
return lambda: new_id
1604
new_test.id = make_new_test_id()
1605
result.addTest(new_test)
1609
def default_test_list():
1610
"""Generate the default list of interrepo permutations to test."""
1611
from bzrlib.repofmt import knitrepo, weaverepo
1613
# test the default InterRepository between format 6 and the current
1615
# XXX: robertc 20060220 reinstate this when there are two supported
1616
# formats which do not have an optimal code path between them.
1617
#result.append((InterRepository,
1618
# RepositoryFormat6(),
1619
# RepositoryFormatKnit1()))
1620
for optimiser_class in InterRepository._optimisers:
1621
format_to_test = optimiser_class._get_repo_format_to_test()
1622
if format_to_test is not None:
1623
result.append((optimiser_class,
1624
format_to_test, format_to_test))
1625
# if there are specific combinations we want to use, we can add them
1627
result.append((InterModel1and2,
1628
weaverepo.RepositoryFormat5(),
1629
knitrepo.RepositoryFormatKnit2()))
1630
result.append((InterKnit1and2,
1631
knitrepo.RepositoryFormatKnit1(),
1632
knitrepo.RepositoryFormatKnit2()))
1636
class CopyConverter(object):
1637
"""A repository conversion tool which just performs a copy of the content.
1639
This is slow but quite reliable.
1642
def __init__(self, target_format):
1643
"""Create a CopyConverter.
1645
:param target_format: The format the resulting repository should be.
1647
self.target_format = target_format
1649
def convert(self, repo, pb):
1650
"""Perform the conversion of to_convert, giving feedback via pb.
1652
:param to_convert: The disk object to convert.
1653
:param pb: a progress bar to use for progress information.
1658
# this is only useful with metadir layouts - separated repo content.
1659
# trigger an assertion if not such
1660
repo._format.get_format_string()
1661
self.repo_dir = repo.bzrdir
1662
self.step('Moving repository to repository.backup')
1663
self.repo_dir.transport.move('repository', 'repository.backup')
1664
backup_transport = self.repo_dir.transport.clone('repository.backup')
1665
repo._format.check_conversion_target(self.target_format)
1666
self.source_repo = repo._format.open(self.repo_dir,
1668
_override_transport=backup_transport)
1669
self.step('Creating new repository')
1670
converted = self.target_format.initialize(self.repo_dir,
1671
self.source_repo.is_shared())
1672
converted.lock_write()
1674
self.step('Copying content into repository.')
1675
self.source_repo.copy_content_into(converted)
1678
self.step('Deleting old repository content.')
1679
self.repo_dir.transport.delete_tree('repository.backup')
1680
self.pb.note('repository converted')
1682
def step(self, message):
1683
"""Update the pb by a step."""
1685
self.pb.update(message, self.count, self.total)
1688
class CommitBuilder(object):
1689
"""Provides an interface to build up a commit.
1691
This allows describing a tree to be committed without needing to
1692
know the internals of the format of the repository.
1695
record_root_entry = False
1696
def __init__(self, repository, parents, config, timestamp=None,
1697
timezone=None, committer=None, revprops=None,
1699
"""Initiate a CommitBuilder.
1701
:param repository: Repository to commit to.
1702
:param parents: Revision ids of the parents of the new revision.
1703
:param config: Configuration to use.
1704
:param timestamp: Optional timestamp recorded for commit.
1705
:param timezone: Optional timezone for timestamp.
1706
:param committer: Optional committer to set for commit.
1707
:param revprops: Optional dictionary of revision properties.
1708
:param revision_id: Optional revision id.
1710
self._config = config
1712
if committer is None:
1713
self._committer = self._config.username()
1715
assert isinstance(committer, basestring), type(committer)
1716
self._committer = committer
1718
self.new_inventory = Inventory(None)
1719
self._new_revision_id = revision_id
1720
self.parents = parents
1721
self.repository = repository
1724
if revprops is not None:
1725
self._revprops.update(revprops)
1727
if timestamp is None:
1728
timestamp = time.time()
1729
# Restrict resolution to 1ms
1730
self._timestamp = round(timestamp, 3)
1732
if timezone is None:
1733
self._timezone = osutils.local_time_offset()
1735
self._timezone = int(timezone)
1737
self._generate_revision_if_needed()
1739
def commit(self, message):
1740
"""Make the actual commit.
1742
:return: The revision id of the recorded revision.
1744
rev = _mod_revision.Revision(
1745
timestamp=self._timestamp,
1746
timezone=self._timezone,
1747
committer=self._committer,
1749
inventory_sha1=self.inv_sha1,
1750
revision_id=self._new_revision_id,
1751
properties=self._revprops)
1752
rev.parent_ids = self.parents
1753
self.repository.add_revision(self._new_revision_id, rev,
1754
self.new_inventory, self._config)
1755
return self._new_revision_id
1757
def revision_tree(self):
1758
"""Return the tree that was just committed.
1760
After calling commit() this can be called to get a RevisionTree
1761
representing the newly committed tree. This is preferred to
1762
calling Repository.revision_tree() because that may require
1763
deserializing the inventory, while we already have a copy in
1766
return RevisionTree(self.repository, self.new_inventory,
1767
self._new_revision_id)
1769
def finish_inventory(self):
1770
"""Tell the builder that the inventory is finished."""
1771
if self.new_inventory.root is None:
1772
symbol_versioning.warn('Root entry should be supplied to'
1773
' record_entry_contents, as of bzr 0.10.',
1774
DeprecationWarning, stacklevel=2)
1775
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
1776
self.new_inventory.revision_id = self._new_revision_id
1777
self.inv_sha1 = self.repository.add_inventory(
1778
self._new_revision_id,
1783
def _gen_revision_id(self):
1784
"""Return new revision-id."""
1785
return generate_ids.gen_revision_id(self._config.username(),
1788
def _generate_revision_if_needed(self):
1789
"""Create a revision id if None was supplied.
1791
If the repository can not support user-specified revision ids
1792
they should override this function and raise CannotSetRevisionId
1793
if _new_revision_id is not None.
1795
:raises: CannotSetRevisionId
1797
if self._new_revision_id is None:
1798
self._new_revision_id = self._gen_revision_id()
1800
def record_entry_contents(self, ie, parent_invs, path, tree):
1801
"""Record the content of ie from tree into the commit if needed.
1803
Side effect: sets ie.revision when unchanged
1805
:param ie: An inventory entry present in the commit.
1806
:param parent_invs: The inventories of the parent revisions of the
1808
:param path: The path the entry is at in the tree.
1809
:param tree: The tree which contains this entry and should be used to
1812
if self.new_inventory.root is None and ie.parent_id is not None:
1813
symbol_versioning.warn('Root entry should be supplied to'
1814
' record_entry_contents, as of bzr 0.10.',
1815
DeprecationWarning, stacklevel=2)
1816
self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
1818
self.new_inventory.add(ie)
1820
# ie.revision is always None if the InventoryEntry is considered
1821
# for committing. ie.snapshot will record the correct revision
1822
# which may be the sole parent if it is untouched.
1823
if ie.revision is not None:
1826
# In this revision format, root entries have no knit or weave
1827
if ie is self.new_inventory.root:
1828
# When serializing out to disk and back in
1829
# root.revision is always _new_revision_id
1830
ie.revision = self._new_revision_id
1832
previous_entries = ie.find_previous_heads(
1834
self.repository.weave_store,
1835
self.repository.get_transaction())
1836
# we are creating a new revision for ie in the history store
1838
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
1840
def modified_directory(self, file_id, file_parents):
1841
"""Record the presence of a symbolic link.
1843
:param file_id: The file_id of the link to record.
1844
:param file_parents: The per-file parent revision ids.
1846
self._add_text_to_weave(file_id, [], file_parents.keys())
1848
def modified_file_text(self, file_id, file_parents,
1849
get_content_byte_lines, text_sha1=None,
1851
"""Record the text of file file_id
1853
:param file_id: The file_id of the file to record the text of.
1854
:param file_parents: The per-file parent revision ids.
1855
:param get_content_byte_lines: A callable which will return the byte
1857
:param text_sha1: Optional SHA1 of the file contents.
1858
:param text_size: Optional size of the file contents.
1860
# mutter('storing text of file {%s} in revision {%s} into %r',
1861
# file_id, self._new_revision_id, self.repository.weave_store)
1862
# special case to avoid diffing on renames or
1864
if (len(file_parents) == 1
1865
and text_sha1 == file_parents.values()[0].text_sha1
1866
and text_size == file_parents.values()[0].text_size):
1867
previous_ie = file_parents.values()[0]
1868
versionedfile = self.repository.weave_store.get_weave(file_id,
1869
self.repository.get_transaction())
1870
versionedfile.clone_text(self._new_revision_id,
1871
previous_ie.revision, file_parents.keys())
1872
return text_sha1, text_size
1874
new_lines = get_content_byte_lines()
1875
# TODO: Rather than invoking sha_strings here, _add_text_to_weave
1876
# should return the SHA1 and size
1877
self._add_text_to_weave(file_id, new_lines, file_parents.keys())
1878
return osutils.sha_strings(new_lines), \
1879
sum(map(len, new_lines))
1881
def modified_link(self, file_id, file_parents, link_target):
1882
"""Record the presence of a symbolic link.
1884
:param file_id: The file_id of the link to record.
1885
:param file_parents: The per-file parent revision ids.
1886
:param link_target: Target location of this link.
1888
self._add_text_to_weave(file_id, [], file_parents.keys())
1890
def _add_text_to_weave(self, file_id, new_lines, parents):
1891
versionedfile = self.repository.weave_store.get_weave_or_empty(
1892
file_id, self.repository.get_transaction())
1893
versionedfile.add_lines(self._new_revision_id, parents, new_lines)
1894
versionedfile.clear_cache()
1897
class _CommitBuilder(CommitBuilder):
1898
"""Temporary class so old CommitBuilders are detected properly
1900
Note: CommitBuilder works whether or not root entry is recorded.
1903
record_root_entry = True
1906
class RootCommitBuilder(CommitBuilder):
1907
"""This commitbuilder actually records the root id"""
1909
record_root_entry = True
1911
def record_entry_contents(self, ie, parent_invs, path, tree):
1912
"""Record the content of ie from tree into the commit if needed.
1914
Side effect: sets ie.revision when unchanged
1916
:param ie: An inventory entry present in the commit.
1917
:param parent_invs: The inventories of the parent revisions of the
1919
:param path: The path the entry is at in the tree.
1920
:param tree: The tree which contains this entry and should be used to
1923
assert self.new_inventory.root is not None or ie.parent_id is None
1924
self.new_inventory.add(ie)
1926
# ie.revision is always None if the InventoryEntry is considered
1927
# for committing. ie.snapshot will record the correct revision
1928
# which may be the sole parent if it is untouched.
1929
if ie.revision is not None:
1932
previous_entries = ie.find_previous_heads(
1934
self.repository.weave_store,
1935
self.repository.get_transaction())
1936
# we are creating a new revision for ie in the history store
1938
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
1950
def _unescaper(match, _map=_unescape_map):
1951
return _map[match.group(1)]
1957
def _unescape_xml(data):
1958
"""Unescape predefined XML entities in a string of data."""
1960
if _unescape_re is None:
1961
_unescape_re = re.compile('\&([^;]*);')
1962
return _unescape_re.sub(_unescaper, data)