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, revision_id, inv, parents):
94
"""Add the inventory inv to the repository as revision_id.
96
:param parents: The revision ids of the parents that revision_id
97
is known to have and are in the repository already.
99
returns the sha1 of the serialized inventory.
101
revision_id = osutils.safe_revision_id(revision_id)
102
_mod_revision.check_not_reserved_id(revision_id)
103
assert inv.revision_id is None or inv.revision_id == revision_id, \
104
"Mismatch between inventory revision" \
105
" id and insertion revid (%r, %r)" % (inv.revision_id, revision_id)
106
assert inv.root is not None
107
inv_text = self.serialise_inventory(inv)
108
inv_sha1 = osutils.sha_string(inv_text)
109
inv_vf = self.control_weaves.get_weave('inventory',
110
self.get_transaction())
111
self._inventory_add_lines(inv_vf, revision_id, parents,
112
osutils.split_lines(inv_text))
115
def _inventory_add_lines(self, inv_vf, revision_id, parents, lines):
117
for parent in parents:
119
final_parents.append(parent)
121
inv_vf.add_lines(revision_id, final_parents, lines)
124
def add_revision(self, revision_id, rev, inv=None, config=None):
125
"""Add rev to the revision store as revision_id.
127
:param revision_id: the revision id to use.
128
:param rev: The revision object.
129
:param inv: The inventory for the revision. if None, it will be looked
130
up in the inventory storer
131
:param config: If None no digital signature will be created.
132
If supplied its signature_needed method will be used
133
to determine if a signature should be made.
135
revision_id = osutils.safe_revision_id(revision_id)
136
# TODO: jam 20070210 Shouldn't we check rev.revision_id and
138
_mod_revision.check_not_reserved_id(revision_id)
139
if config is not None and config.signature_needed():
141
inv = self.get_inventory(revision_id)
142
plaintext = Testament(rev, inv).as_short_text()
143
self.store_revision_signature(
144
gpg.GPGStrategy(config), plaintext, revision_id)
145
if not revision_id in self.get_inventory_weave():
147
raise errors.WeaveRevisionNotPresent(revision_id,
148
self.get_inventory_weave())
150
# yes, this is not suitable for adding with ghosts.
151
self.add_inventory(revision_id, inv, rev.parent_ids)
152
self._revision_store.add_revision(rev, self.get_transaction())
155
def _all_possible_ids(self):
156
"""Return all the possible revisions that we could find."""
157
return self.get_inventory_weave().versions()
159
def all_revision_ids(self):
160
"""Returns a list of all the revision ids in the repository.
162
This is deprecated because code should generally work on the graph
163
reachable from a particular revision, and ignore any other revisions
164
that might be present. There is no direct replacement method.
166
return self._all_revision_ids()
169
def _all_revision_ids(self):
170
"""Returns a list of all the revision ids in the repository.
172
These are in as much topological order as the underlying store can
173
present: for weaves ghosts may lead to a lack of correctness until
174
the reweave updates the parents list.
176
if self._revision_store.text_store.listable():
177
return self._revision_store.all_revision_ids(self.get_transaction())
178
result = self._all_possible_ids()
179
# TODO: jam 20070210 Ensure that _all_possible_ids returns non-unicode
180
# ids. (It should, since _revision_store's API should change to
181
# return utf8 revision_ids)
182
return self._eliminate_revisions_not_present(result)
184
def break_lock(self):
185
"""Break a lock if one is present from another instance.
187
Uses the ui factory to ask for confirmation if the lock may be from
190
self.control_files.break_lock()
193
def _eliminate_revisions_not_present(self, revision_ids):
194
"""Check every revision id in revision_ids to see if we have it.
196
Returns a set of the present revisions.
199
for id in revision_ids:
200
if self.has_revision(id):
205
def create(a_bzrdir):
206
"""Construct the current default format repository in a_bzrdir."""
207
return RepositoryFormat.get_default_format().initialize(a_bzrdir)
209
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
210
"""instantiate a Repository.
212
:param _format: The format of the repository on disk.
213
:param a_bzrdir: The BzrDir of the repository.
215
In the future we will have a single api for all stores for
216
getting file texts, inventories and revisions, then
217
this construct will accept instances of those things.
219
super(Repository, self).__init__()
220
self._format = _format
221
# the following are part of the public API for Repository:
222
self.bzrdir = a_bzrdir
223
self.control_files = control_files
224
self._revision_store = _revision_store
225
self.text_store = text_store
226
# backwards compatibility
227
self.weave_store = text_store
228
# not right yet - should be more semantically clear ?
230
self.control_store = control_store
231
self.control_weaves = control_store
232
# TODO: make sure to construct the right store classes, etc, depending
233
# on whether escaping is required.
234
self._warn_if_deprecated()
235
self._serializer = xml5.serializer_v5
238
return '%s(%r)' % (self.__class__.__name__,
239
self.bzrdir.transport.base)
242
return self.control_files.is_locked()
244
def lock_write(self):
245
self.control_files.lock_write()
248
self.control_files.lock_read()
250
def get_physical_lock_status(self):
251
return self.control_files.get_physical_lock_status()
254
def missing_revision_ids(self, other, revision_id=None):
255
"""Return the revision ids that other has that this does not.
257
These are returned in topological order.
259
revision_id: only return revision ids included by revision_id.
261
revision_id = osutils.safe_revision_id(revision_id)
262
return InterRepository.get(other, self).missing_revision_ids(revision_id)
266
"""Open the repository rooted at base.
268
For instance, if the repository is at URL/.bzr/repository,
269
Repository.open(URL) -> a Repository instance.
271
control = bzrdir.BzrDir.open(base)
272
return control.open_repository()
274
def copy_content_into(self, destination, revision_id=None, basis=None):
275
"""Make a complete copy of the content in self into destination.
277
This is a destructive operation! Do not use it on existing
280
revision_id = osutils.safe_revision_id(revision_id)
281
return InterRepository.get(self, destination).copy_content(revision_id, basis)
283
def fetch(self, source, revision_id=None, pb=None):
284
"""Fetch the content required to construct revision_id from source.
286
If revision_id is None all content is copied.
288
revision_id = osutils.safe_revision_id(revision_id)
289
return InterRepository.get(source, self).fetch(revision_id=revision_id,
292
def get_commit_builder(self, branch, parents, config, timestamp=None,
293
timezone=None, committer=None, revprops=None,
295
"""Obtain a CommitBuilder for this repository.
297
:param branch: Branch to commit to.
298
:param parents: Revision ids of the parents of the new revision.
299
:param config: Configuration to use.
300
:param timestamp: Optional timestamp recorded for commit.
301
:param timezone: Optional timezone for timestamp.
302
:param committer: Optional committer to set for commit.
303
:param revprops: Optional dictionary of revision properties.
304
:param revision_id: Optional revision id.
306
revision_id = osutils.safe_revision_id(revision_id)
307
return _CommitBuilder(self, parents, config, timestamp, timezone,
308
committer, revprops, revision_id)
311
self.control_files.unlock()
314
def clone(self, a_bzrdir, revision_id=None, basis=None):
315
"""Clone this repository into a_bzrdir using the current format.
317
Currently no check is made that the format of this repository and
318
the bzrdir format are compatible. FIXME RBC 20060201.
320
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
321
# use target default format.
322
result = a_bzrdir.create_repository()
323
# FIXME RBC 20060209 split out the repository type to avoid this check ?
324
elif isinstance(a_bzrdir._format,
325
(bzrdir.BzrDirFormat4,
326
bzrdir.BzrDirFormat5,
327
bzrdir.BzrDirFormat6)):
328
result = a_bzrdir.open_repository()
330
result = self._format.initialize(a_bzrdir, shared=self.is_shared())
331
self.copy_content_into(result, revision_id, basis)
335
def has_revision(self, revision_id):
336
"""True if this repository has a copy of the revision."""
337
revision_id = osutils.safe_revision_id(revision_id)
338
return self._revision_store.has_revision_id(revision_id,
339
self.get_transaction())
342
def get_revision_reconcile(self, revision_id):
343
"""'reconcile' helper routine that allows access to a revision always.
345
This variant of get_revision does not cross check the weave graph
346
against the revision one as get_revision does: but it should only
347
be used by reconcile, or reconcile-alike commands that are correcting
348
or testing the revision graph.
350
if not revision_id or not isinstance(revision_id, basestring):
351
raise errors.InvalidRevisionId(revision_id=revision_id,
353
return self.get_revisions([revision_id])[0]
356
def get_revisions(self, revision_ids):
357
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
358
revs = self._revision_store.get_revisions(revision_ids,
359
self.get_transaction())
361
assert not isinstance(rev.revision_id, unicode)
362
for parent_id in rev.parent_ids:
363
assert not isinstance(parent_id, unicode)
367
def get_revision_xml(self, revision_id):
368
# TODO: jam 20070210 This shouldn't be necessary since get_revision
369
# would have already do it.
370
# TODO: jam 20070210 Just use _serializer.write_revision_to_string()
371
revision_id = osutils.safe_revision_id(revision_id)
372
rev = self.get_revision(revision_id)
374
# the current serializer..
375
self._revision_store._serializer.write_revision(rev, rev_tmp)
377
return rev_tmp.getvalue()
380
def get_revision(self, revision_id):
381
"""Return the Revision object for a named revision"""
382
# TODO: jam 20070210 get_revision_reconcile should do this for us
383
revision_id = osutils.safe_revision_id(revision_id)
384
r = self.get_revision_reconcile(revision_id)
385
# weave corruption can lead to absent revision markers that should be
387
# the following test is reasonably cheap (it needs a single weave read)
388
# and the weave is cached in read transactions. In write transactions
389
# it is not cached but typically we only read a small number of
390
# revisions. For knits when they are introduced we will probably want
391
# to ensure that caching write transactions are in use.
392
inv = self.get_inventory_weave()
393
self._check_revision_parents(r, inv)
397
def get_deltas_for_revisions(self, revisions):
398
"""Produce a generator of revision deltas.
400
Note that the input is a sequence of REVISIONS, not revision_ids.
401
Trees will be held in memory until the generator exits.
402
Each delta is relative to the revision's lefthand predecessor.
404
required_trees = set()
405
for revision in revisions:
406
required_trees.add(revision.revision_id)
407
required_trees.update(revision.parent_ids[:1])
408
trees = dict((t.get_revision_id(), t) for
409
t in self.revision_trees(required_trees))
410
for revision in revisions:
411
if not revision.parent_ids:
412
old_tree = self.revision_tree(None)
414
old_tree = trees[revision.parent_ids[0]]
415
yield trees[revision.revision_id].changes_from(old_tree)
418
def get_revision_delta(self, revision_id):
419
"""Return the delta for one revision.
421
The delta is relative to the left-hand predecessor of the
424
r = self.get_revision(revision_id)
425
return list(self.get_deltas_for_revisions([r]))[0]
427
def _check_revision_parents(self, revision, inventory):
428
"""Private to Repository and Fetch.
430
This checks the parentage of revision in an inventory weave for
431
consistency and is only applicable to inventory-weave-for-ancestry
432
using repository formats & fetchers.
434
weave_parents = inventory.get_parents(revision.revision_id)
435
weave_names = inventory.versions()
436
for parent_id in revision.parent_ids:
437
if parent_id in weave_names:
438
# this parent must not be a ghost.
439
if not parent_id in weave_parents:
441
raise errors.CorruptRepository(self)
444
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
445
revision_id = osutils.safe_revision_id(revision_id)
446
signature = gpg_strategy.sign(plaintext)
447
self._revision_store.add_revision_signature_text(revision_id,
449
self.get_transaction())
451
def fileids_altered_by_revision_ids(self, revision_ids):
452
"""Find the file ids and versions affected by revisions.
454
:param revisions: an iterable containing revision ids.
455
:return: a dictionary mapping altered file-ids to an iterable of
456
revision_ids. Each altered file-ids has the exact revision_ids that
457
altered it listed explicitly.
459
assert self._serializer.support_altered_by_hack, \
460
("fileids_altered_by_revision_ids only supported for branches "
461
"which store inventory as unnested xml, not on %r" % self)
462
selected_revision_ids = set(osutils.safe_revision_id(r)
463
for r in revision_ids)
464
w = self.get_inventory_weave()
467
# this code needs to read every new line in every inventory for the
468
# inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
469
# not present in one of those inventories is unnecessary but not
470
# harmful because we are filtering by the revision id marker in the
471
# inventory lines : we only select file ids altered in one of those
472
# revisions. We don't need to see all lines in the inventory because
473
# only those added in an inventory in rev X can contain a revision=X
475
unescape_revid_cache = {}
476
unescape_fileid_cache = {}
478
# jam 20061218 In a big fetch, this handles hundreds of thousands
479
# of lines, so it has had a lot of inlining and optimizing done.
480
# Sorry that it is a little bit messy.
481
# Move several functions to be local variables, since this is a long
483
search = self._file_ids_altered_regex.search
484
unescape = _unescape_xml
485
setdefault = result.setdefault
486
pb = ui.ui_factory.nested_progress_bar()
488
for line in w.iter_lines_added_or_present_in_versions(
489
selected_revision_ids, pb=pb):
493
# One call to match.group() returning multiple items is quite a
494
# bit faster than 2 calls to match.group() each returning 1
495
file_id, revision_id = match.group('file_id', 'revision_id')
497
# Inlining the cache lookups helps a lot when you make 170,000
498
# lines and 350k ids, versus 8.4 unique ids.
499
# Using a cache helps in 2 ways:
500
# 1) Avoids unnecessary decoding calls
501
# 2) Re-uses cached strings, which helps in future set and
503
# (2) is enough that removing encoding entirely along with
504
# the cache (so we are using plain strings) results in no
505
# performance improvement.
507
revision_id = unescape_revid_cache[revision_id]
509
unescaped = unescape(revision_id)
510
unescape_revid_cache[revision_id] = unescaped
511
revision_id = unescaped
513
if revision_id in selected_revision_ids:
515
file_id = unescape_fileid_cache[file_id]
517
unescaped = unescape(file_id)
518
unescape_fileid_cache[file_id] = unescaped
520
setdefault(file_id, set()).add(revision_id)
526
def get_inventory_weave(self):
527
return self.control_weaves.get_weave('inventory',
528
self.get_transaction())
531
def get_inventory(self, revision_id):
532
"""Get Inventory object by hash."""
533
# TODO: jam 20070210 Technically we don't need to sanitize, since all
534
# called functions must sanitize.
535
revision_id = osutils.safe_revision_id(revision_id)
536
return self.deserialise_inventory(
537
revision_id, self.get_inventory_xml(revision_id))
539
def deserialise_inventory(self, revision_id, xml):
540
"""Transform the xml into an inventory object.
542
:param revision_id: The expected revision id of the inventory.
543
:param xml: A serialised inventory.
545
revision_id = osutils.safe_revision_id(revision_id)
546
result = self._serializer.read_inventory_from_string(xml)
547
result.root.revision = revision_id
550
def serialise_inventory(self, inv):
551
return self._serializer.write_inventory_to_string(inv)
554
def get_inventory_xml(self, revision_id):
555
"""Get inventory XML as a file object."""
556
revision_id = osutils.safe_revision_id(revision_id)
558
assert isinstance(revision_id, str), type(revision_id)
559
iw = self.get_inventory_weave()
560
return iw.get_text(revision_id)
562
raise errors.HistoryMissing(self, 'inventory', revision_id)
565
def get_inventory_sha1(self, revision_id):
566
"""Return the sha1 hash of the inventory entry
568
# TODO: jam 20070210 Shouldn't this be deprecated / removed?
569
revision_id = osutils.safe_revision_id(revision_id)
570
return self.get_revision(revision_id).inventory_sha1
573
def get_revision_graph(self, revision_id=None):
574
"""Return a dictionary containing the revision graph.
576
:param revision_id: The revision_id to get a graph from. If None, then
577
the entire revision graph is returned. This is a deprecated mode of
578
operation and will be removed in the future.
579
:return: a dictionary of revision_id->revision_parents_list.
581
# special case NULL_REVISION
582
if revision_id == _mod_revision.NULL_REVISION:
584
revision_id = osutils.safe_revision_id(revision_id)
585
a_weave = self.get_inventory_weave()
586
all_revisions = self._eliminate_revisions_not_present(
588
entire_graph = dict([(node, a_weave.get_parents(node)) for
589
node in all_revisions])
590
if revision_id is None:
592
elif revision_id not in entire_graph:
593
raise errors.NoSuchRevision(self, revision_id)
595
# add what can be reached from revision_id
597
pending = set([revision_id])
598
while len(pending) > 0:
600
result[node] = entire_graph[node]
601
for revision_id in result[node]:
602
if revision_id not in result:
603
pending.add(revision_id)
607
def get_revision_graph_with_ghosts(self, revision_ids=None):
608
"""Return a graph of the revisions with ghosts marked as applicable.
610
:param revision_ids: an iterable of revisions to graph or None for all.
611
:return: a Graph object with the graph reachable from revision_ids.
613
result = graph.Graph()
615
pending = set(self.all_revision_ids())
618
pending = set(osutils.safe_revision_id(r) for r in revision_ids)
619
# special case NULL_REVISION
620
if _mod_revision.NULL_REVISION in pending:
621
pending.remove(_mod_revision.NULL_REVISION)
622
required = set(pending)
625
revision_id = pending.pop()
627
rev = self.get_revision(revision_id)
628
except errors.NoSuchRevision:
629
if revision_id in required:
632
result.add_ghost(revision_id)
634
for parent_id in rev.parent_ids:
635
# is this queued or done ?
636
if (parent_id not in pending and
637
parent_id not in done):
639
pending.add(parent_id)
640
result.add_node(revision_id, rev.parent_ids)
641
done.add(revision_id)
645
def get_revision_inventory(self, revision_id):
646
"""Return inventory of a past revision."""
647
# TODO: Unify this with get_inventory()
648
# bzr 0.0.6 and later imposes the constraint that the inventory_id
649
# must be the same as its revision, so this is trivial.
650
if revision_id is None:
651
# This does not make sense: if there is no revision,
652
# then it is the current tree inventory surely ?!
653
# and thus get_root_id() is something that looks at the last
654
# commit on the branch, and the get_root_id is an inventory check.
655
raise NotImplementedError
656
# return Inventory(self.get_root_id())
658
return self.get_inventory(revision_id)
662
"""Return True if this repository is flagged as a shared repository."""
663
raise NotImplementedError(self.is_shared)
666
def reconcile(self, other=None, thorough=False):
667
"""Reconcile this repository."""
668
from bzrlib.reconcile import RepoReconciler
669
reconciler = RepoReconciler(self, thorough=thorough)
670
reconciler.reconcile()
674
def revision_tree(self, revision_id):
675
"""Return Tree for a revision on this branch.
677
`revision_id` may be None for the empty tree revision.
679
# TODO: refactor this to use an existing revision object
680
# so we don't need to read it in twice.
681
if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
682
return RevisionTree(self, Inventory(root_id=None),
683
_mod_revision.NULL_REVISION)
685
revision_id = osutils.safe_revision_id(revision_id)
686
inv = self.get_revision_inventory(revision_id)
687
return RevisionTree(self, inv, revision_id)
690
def revision_trees(self, revision_ids):
691
"""Return Tree for a revision on this branch.
693
`revision_id` may not be None or 'null:'"""
694
assert None not in revision_ids
695
assert _mod_revision.NULL_REVISION not in revision_ids
696
texts = self.get_inventory_weave().get_texts(revision_ids)
697
for text, revision_id in zip(texts, revision_ids):
698
inv = self.deserialise_inventory(revision_id, text)
699
yield RevisionTree(self, inv, revision_id)
702
def get_ancestry(self, revision_id):
703
"""Return a list of revision-ids integrated by a revision.
705
The first element of the list is always None, indicating the origin
706
revision. This might change when we have history horizons, or
707
perhaps we should have a new API.
709
This is topologically sorted.
711
if revision_id is None:
713
revision_id = osutils.safe_revision_id(revision_id)
714
if not self.has_revision(revision_id):
715
raise errors.NoSuchRevision(self, revision_id)
716
w = self.get_inventory_weave()
717
candidates = w.get_ancestry(revision_id)
718
return [None] + candidates # self._eliminate_revisions_not_present(candidates)
721
def print_file(self, file, revision_id):
722
"""Print `file` to stdout.
724
FIXME RBC 20060125 as John Meinel points out this is a bad api
725
- it writes to stdout, it assumes that that is valid etc. Fix
726
by creating a new more flexible convenience function.
728
revision_id = osutils.safe_revision_id(revision_id)
729
tree = self.revision_tree(revision_id)
730
# use inventory as it was in that revision
731
file_id = tree.inventory.path2id(file)
733
# TODO: jam 20060427 Write a test for this code path
734
# it had a bug in it, and was raising the wrong
736
raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
737
tree.print_file(file_id)
739
def get_transaction(self):
740
return self.control_files.get_transaction()
742
def revision_parents(self, revision_id):
743
revision_id = osutils.safe_revision_id(revision_id)
744
return self.get_inventory_weave().parent_names(revision_id)
747
def set_make_working_trees(self, new_value):
748
"""Set the policy flag for making working trees when creating branches.
750
This only applies to branches that use this repository.
752
The default is 'True'.
753
:param new_value: True to restore the default, False to disable making
756
raise NotImplementedError(self.set_make_working_trees)
758
def make_working_trees(self):
759
"""Returns the policy for making working trees on new branches."""
760
raise NotImplementedError(self.make_working_trees)
763
def sign_revision(self, revision_id, gpg_strategy):
764
revision_id = osutils.safe_revision_id(revision_id)
765
plaintext = Testament.from_revision(self, revision_id).as_short_text()
766
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
769
def has_signature_for_revision_id(self, revision_id):
770
"""Query for a revision signature for revision_id in the repository."""
771
revision_id = osutils.safe_revision_id(revision_id)
772
return self._revision_store.has_signature(revision_id,
773
self.get_transaction())
776
def get_signature_text(self, revision_id):
777
"""Return the text for a signature."""
778
revision_id = osutils.safe_revision_id(revision_id)
779
return self._revision_store.get_signature_text(revision_id,
780
self.get_transaction())
783
def check(self, revision_ids):
784
"""Check consistency of all history of given revision_ids.
786
Different repository implementations should override _check().
788
:param revision_ids: A non-empty list of revision_ids whose ancestry
789
will be checked. Typically the last revision_id of a branch.
792
raise ValueError("revision_ids must be non-empty in %s.check"
794
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
795
return self._check(revision_ids)
797
def _check(self, revision_ids):
798
result = check.Check(self)
802
def _warn_if_deprecated(self):
803
global _deprecation_warning_done
804
if _deprecation_warning_done:
806
_deprecation_warning_done = True
807
warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
808
% (self._format, self.bzrdir.transport.base))
810
def supports_rich_root(self):
811
return self._format.rich_root_data
813
def _check_ascii_revisionid(self, revision_id, method):
814
"""Private helper for ascii-only repositories."""
815
# weave repositories refuse to store revisionids that are non-ascii.
816
if revision_id is not None:
817
# weaves require ascii revision ids.
818
if isinstance(revision_id, unicode):
820
revision_id.encode('ascii')
821
except UnicodeEncodeError:
822
raise errors.NonAsciiRevisionId(method, self)
825
revision_id.decode('ascii')
826
except UnicodeDecodeError:
827
raise errors.NonAsciiRevisionId(method, self)
830
class AllInOneRepository(Repository):
831
"""Legacy support - the repository behaviour for all-in-one branches."""
833
def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
834
# we reuse one control files instance.
835
dir_mode = a_bzrdir._control_files._dir_mode
836
file_mode = a_bzrdir._control_files._file_mode
838
def get_store(name, compressed=True, prefixed=False):
839
# FIXME: This approach of assuming stores are all entirely compressed
840
# or entirely uncompressed is tidy, but breaks upgrade from
841
# some existing branches where there's a mixture; we probably
842
# still want the option to look for both.
843
relpath = a_bzrdir._control_files._escape(name)
844
store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
845
prefixed=prefixed, compressed=compressed,
848
#if self._transport.should_cache():
849
# cache_path = os.path.join(self.cache_root, name)
850
# os.mkdir(cache_path)
851
# store = bzrlib.store.CachedStore(store, cache_path)
854
# not broken out yet because the controlweaves|inventory_store
855
# and text_store | weave_store bits are still different.
856
if isinstance(_format, RepositoryFormat4):
857
# cannot remove these - there is still no consistent api
858
# which allows access to this old info.
859
self.inventory_store = get_store('inventory-store')
860
text_store = get_store('text-store')
861
super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
863
def get_commit_builder(self, branch, parents, config, timestamp=None,
864
timezone=None, committer=None, revprops=None,
866
self._check_ascii_revisionid(revision_id, self.get_commit_builder)
867
return Repository.get_commit_builder(self, branch, parents, config,
868
timestamp, timezone, committer, revprops, revision_id)
872
"""AllInOne repositories cannot be shared."""
876
def set_make_working_trees(self, new_value):
877
"""Set the policy flag for making working trees when creating branches.
879
This only applies to branches that use this repository.
881
The default is 'True'.
882
:param new_value: True to restore the default, False to disable making
885
raise NotImplementedError(self.set_make_working_trees)
887
def make_working_trees(self):
888
"""Returns the policy for making working trees on new branches."""
892
def install_revision(repository, rev, revision_tree):
893
"""Install all revision data into a repository."""
896
for p_id in rev.parent_ids:
897
if repository.has_revision(p_id):
898
present_parents.append(p_id)
899
parent_trees[p_id] = repository.revision_tree(p_id)
901
parent_trees[p_id] = repository.revision_tree(None)
903
inv = revision_tree.inventory
904
entries = inv.iter_entries()
905
# backwards compatability hack: skip the root id.
906
if not repository.supports_rich_root():
907
path, root = entries.next()
908
if root.revision != rev.revision_id:
909
raise errors.IncompatibleRevision(repr(repository))
910
# Add the texts that are not already present
911
for path, ie in entries:
912
w = repository.weave_store.get_weave_or_empty(ie.file_id,
913
repository.get_transaction())
914
if ie.revision not in w:
916
# FIXME: TODO: The following loop *may* be overlapping/duplicate
917
# with InventoryEntry.find_previous_heads(). if it is, then there
918
# is a latent bug here where the parents may have ancestors of each
920
for revision, tree in parent_trees.iteritems():
921
if ie.file_id not in tree:
923
parent_id = tree.inventory[ie.file_id].revision
924
if parent_id in text_parents:
926
text_parents.append(parent_id)
928
vfile = repository.weave_store.get_weave_or_empty(ie.file_id,
929
repository.get_transaction())
930
lines = revision_tree.get_file(ie.file_id).readlines()
931
vfile.add_lines(rev.revision_id, text_parents, lines)
933
# install the inventory
934
repository.add_inventory(rev.revision_id, inv, present_parents)
935
except errors.RevisionAlreadyPresent:
937
repository.add_revision(rev.revision_id, rev, inv)
940
class MetaDirRepository(Repository):
941
"""Repositories in the new meta-dir layout."""
943
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
944
super(MetaDirRepository, self).__init__(_format,
950
dir_mode = self.control_files._dir_mode
951
file_mode = self.control_files._file_mode
955
"""Return True if this repository is flagged as a shared repository."""
956
return self.control_files._transport.has('shared-storage')
959
def set_make_working_trees(self, new_value):
960
"""Set the policy flag for making working trees when creating branches.
962
This only applies to branches that use this repository.
964
The default is 'True'.
965
:param new_value: True to restore the default, False to disable making
970
self.control_files._transport.delete('no-working-trees')
971
except errors.NoSuchFile:
974
self.control_files.put_utf8('no-working-trees', '')
976
def make_working_trees(self):
977
"""Returns the policy for making working trees on new branches."""
978
return not self.control_files._transport.has('no-working-trees')
981
class WeaveMetaDirRepository(MetaDirRepository):
982
"""A subclass of MetaDirRepository to set weave specific policy."""
984
def get_commit_builder(self, branch, parents, config, timestamp=None,
985
timezone=None, committer=None, revprops=None,
987
self._check_ascii_revisionid(revision_id, self.get_commit_builder)
988
return MetaDirRepository.get_commit_builder(self, branch, parents,
989
config, timestamp, timezone, committer, revprops, revision_id)
992
class KnitRepository(MetaDirRepository):
993
"""Knit format repository."""
995
def _warn_if_deprecated(self):
996
# This class isn't deprecated
999
def _inventory_add_lines(self, inv_vf, revid, parents, lines):
1000
inv_vf.add_lines_with_ghosts(revid, parents, lines)
1003
def _all_revision_ids(self):
1004
"""See Repository.all_revision_ids()."""
1005
# Knits get the revision graph from the index of the revision knit, so
1006
# it's always possible even if they're on an unlistable transport.
1007
return self._revision_store.all_revision_ids(self.get_transaction())
1009
def fileid_involved_between_revs(self, from_revid, to_revid):
1010
"""Find file_id(s) which are involved in the changes between revisions.
1012
This determines the set of revisions which are involved, and then
1013
finds all file ids affected by those revisions.
1015
# TODO: jam 20070210 Is this function even used?
1016
from_revid = osutils.safe_revision_id(from_revid)
1017
to_revid = osutils.safe_revision_id(to_revid)
1018
vf = self._get_revision_vf()
1019
from_set = set(vf.get_ancestry(from_revid))
1020
to_set = set(vf.get_ancestry(to_revid))
1021
changed = to_set.difference(from_set)
1022
return self._fileid_involved_by_set(changed)
1024
def fileid_involved(self, last_revid=None):
1025
"""Find all file_ids modified in the ancestry of last_revid.
1027
:param last_revid: If None, last_revision() will be used.
1029
# TODO: jam 20070210 Is this used anymore?
1031
changed = set(self.all_revision_ids())
1033
changed = set(self.get_ancestry(last_revid))
1035
changed.remove(None)
1036
return self._fileid_involved_by_set(changed)
1039
def get_ancestry(self, revision_id):
1040
"""Return a list of revision-ids integrated by a revision.
1042
This is topologically sorted.
1044
if revision_id is None:
1046
revision_id = osutils.safe_revision_id(revision_id)
1047
vf = self._get_revision_vf()
1049
return [None] + vf.get_ancestry(revision_id)
1050
except errors.RevisionNotPresent:
1051
raise errors.NoSuchRevision(self, revision_id)
1054
def get_revision(self, revision_id):
1055
"""Return the Revision object for a named revision"""
1056
revision_id = osutils.safe_revision_id(revision_id)
1057
return self.get_revision_reconcile(revision_id)
1060
def get_revision_graph(self, revision_id=None):
1061
"""Return a dictionary containing the revision graph.
1063
:param revision_id: The revision_id to get a graph from. If None, then
1064
the entire revision graph is returned. This is a deprecated mode of
1065
operation and will be removed in the future.
1066
:return: a dictionary of revision_id->revision_parents_list.
1068
# special case NULL_REVISION
1069
if revision_id == _mod_revision.NULL_REVISION:
1071
revision_id = osutils.safe_revision_id(revision_id)
1072
a_weave = self._get_revision_vf()
1073
entire_graph = a_weave.get_graph()
1074
if revision_id is None:
1075
return a_weave.get_graph()
1076
elif revision_id not in a_weave:
1077
raise errors.NoSuchRevision(self, revision_id)
1079
# add what can be reached from revision_id
1081
pending = set([revision_id])
1082
while len(pending) > 0:
1083
node = pending.pop()
1084
result[node] = a_weave.get_parents(node)
1085
for revision_id in result[node]:
1086
if revision_id not in result:
1087
pending.add(revision_id)
1091
def get_revision_graph_with_ghosts(self, revision_ids=None):
1092
"""Return a graph of the revisions with ghosts marked as applicable.
1094
:param revision_ids: an iterable of revisions to graph or None for all.
1095
:return: a Graph object with the graph reachable from revision_ids.
1097
result = graph.Graph()
1098
vf = self._get_revision_vf()
1099
versions = set(vf.versions())
1100
if not revision_ids:
1101
pending = set(self.all_revision_ids())
1104
pending = set(osutils.safe_revision_id(r) for r in revision_ids)
1105
# special case NULL_REVISION
1106
if _mod_revision.NULL_REVISION in pending:
1107
pending.remove(_mod_revision.NULL_REVISION)
1108
required = set(pending)
1111
revision_id = pending.pop()
1112
if not revision_id in versions:
1113
if revision_id in required:
1114
raise errors.NoSuchRevision(self, revision_id)
1116
result.add_ghost(revision_id)
1117
# mark it as done so we don't try for it again.
1118
done.add(revision_id)
1120
parent_ids = vf.get_parents_with_ghosts(revision_id)
1121
for parent_id in parent_ids:
1122
# is this queued or done ?
1123
if (parent_id not in pending and
1124
parent_id not in done):
1126
pending.add(parent_id)
1127
result.add_node(revision_id, parent_ids)
1128
done.add(revision_id)
1131
def _get_revision_vf(self):
1132
""":return: a versioned file containing the revisions."""
1133
vf = self._revision_store.get_revision_file(self.get_transaction())
1137
def reconcile(self, other=None, thorough=False):
1138
"""Reconcile this repository."""
1139
from bzrlib.reconcile import KnitReconciler
1140
reconciler = KnitReconciler(self, thorough=thorough)
1141
reconciler.reconcile()
1144
def revision_parents(self, revision_id):
1145
revision_id = osutils.safe_revision_id(revision_id)
1146
return self._get_revision_vf().get_parents(revision_id)
1149
class KnitRepository2(KnitRepository):
1151
def __init__(self, _format, a_bzrdir, control_files, _revision_store,
1152
control_store, text_store):
1153
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
1154
_revision_store, control_store, text_store)
1155
self._serializer = xml6.serializer_v6
1157
def deserialise_inventory(self, revision_id, xml):
1158
"""Transform the xml into an inventory object.
1160
:param revision_id: The expected revision id of the inventory.
1161
:param xml: A serialised inventory.
1163
result = self._serializer.read_inventory_from_string(xml)
1164
assert result.root.revision is not None
1167
def serialise_inventory(self, inv):
1168
"""Transform the inventory object into XML text.
1170
:param revision_id: The expected revision id of the inventory.
1171
:param xml: A serialised inventory.
1173
assert inv.revision_id is not None
1174
assert inv.root.revision is not None
1175
return KnitRepository.serialise_inventory(self, inv)
1177
def get_commit_builder(self, branch, parents, config, timestamp=None,
1178
timezone=None, committer=None, revprops=None,
1180
"""Obtain a CommitBuilder for this repository.
1182
:param branch: Branch to commit to.
1183
:param parents: Revision ids of the parents of the new revision.
1184
:param config: Configuration to use.
1185
:param timestamp: Optional timestamp recorded for commit.
1186
:param timezone: Optional timezone for timestamp.
1187
:param committer: Optional committer to set for commit.
1188
:param revprops: Optional dictionary of revision properties.
1189
:param revision_id: Optional revision id.
1191
revision_id = osutils.safe_revision_id(revision_id)
1192
return RootCommitBuilder(self, parents, config, timestamp, timezone,
1193
committer, revprops, revision_id)
1196
class RepositoryFormatRegistry(registry.Registry):
1197
"""Registry of RepositoryFormats.
1201
format_registry = RepositoryFormatRegistry()
1202
"""Registry of formats, indexed by their identifying format string."""
1205
class RepositoryFormat(object):
1206
"""A repository format.
1208
Formats provide three things:
1209
* An initialization routine to construct repository data on disk.
1210
* a format string which is used when the BzrDir supports versioned
1212
* an open routine which returns a Repository instance.
1214
Formats are placed in an dict by their format string for reference
1215
during opening. These should be subclasses of RepositoryFormat
1218
Once a format is deprecated, just deprecate the initialize and open
1219
methods on the format class. Do not deprecate the object, as the
1220
object will be created every system load.
1222
Common instance attributes:
1223
_matchingbzrdir - the bzrdir format that the repository format was
1224
originally written to work with. This can be used if manually
1225
constructing a bzrdir and repository, or more commonly for test suite
1230
return "<%s>" % self.__class__.__name__
1233
def find_format(klass, a_bzrdir):
1234
"""Return the format for the repository object in a_bzrdir.
1236
This is used by bzr native formats that have a "format" file in
1237
the repository. Other methods may be used by different types of
1241
transport = a_bzrdir.get_repository_transport(None)
1242
format_string = transport.get("format").read()
1243
return format_registry.get(format_string)
1244
except errors.NoSuchFile:
1245
raise errors.NoRepositoryPresent(a_bzrdir)
1247
raise errors.UnknownFormatError(format=format_string)
1250
@deprecated_method(symbol_versioning.zero_fourteen)
1251
def set_default_format(klass, format):
1252
klass._set_default_format(format)
1255
def _set_default_format(klass, format):
1256
"""Set the default format for new Repository creation.
1258
The format must already be registered.
1260
format_registry.default_key = format.get_format_string()
1263
def register_format(klass, format):
1264
format_registry.register(format.get_format_string(), format)
1267
def unregister_format(klass, format):
1268
format_registry.remove(format.get_format_string())
1271
def get_default_format(klass):
1272
"""Return the current default format."""
1273
return format_registry.get(format_registry.default_key)
1275
def _get_control_store(self, repo_transport, control_files):
1276
"""Return the control store for this repository."""
1277
raise NotImplementedError(self._get_control_store)
1279
def get_format_string(self):
1280
"""Return the ASCII format string that identifies this format.
1282
Note that in pre format ?? repositories the format string is
1283
not permitted nor written to disk.
1285
raise NotImplementedError(self.get_format_string)
1287
def get_format_description(self):
1288
"""Return the short description for this format."""
1289
raise NotImplementedError(self.get_format_description)
1291
def _get_revision_store(self, repo_transport, control_files):
1292
"""Return the revision store object for this a_bzrdir."""
1293
raise NotImplementedError(self._get_revision_store)
1295
def _get_text_rev_store(self,
1302
"""Common logic for getting a revision store for a repository.
1304
see self._get_revision_store for the subclass-overridable method to
1305
get the store for a repository.
1307
from bzrlib.store.revision.text import TextRevisionStore
1308
dir_mode = control_files._dir_mode
1309
file_mode = control_files._file_mode
1310
text_store =TextStore(transport.clone(name),
1312
compressed=compressed,
1314
file_mode=file_mode)
1315
_revision_store = TextRevisionStore(text_store, serializer)
1316
return _revision_store
1318
def _get_versioned_file_store(self,
1323
versionedfile_class=weave.WeaveFile,
1324
versionedfile_kwargs={},
1326
weave_transport = control_files._transport.clone(name)
1327
dir_mode = control_files._dir_mode
1328
file_mode = control_files._file_mode
1329
return VersionedFileStore(weave_transport, prefixed=prefixed,
1331
file_mode=file_mode,
1332
versionedfile_class=versionedfile_class,
1333
versionedfile_kwargs=versionedfile_kwargs,
1336
def initialize(self, a_bzrdir, shared=False):
1337
"""Initialize a repository of this format in a_bzrdir.
1339
:param a_bzrdir: The bzrdir to put the new repository in it.
1340
:param shared: The repository should be initialized as a sharable one.
1342
This may raise UninitializableFormat if shared repository are not
1343
compatible the a_bzrdir.
1346
def is_supported(self):
1347
"""Is this format supported?
1349
Supported formats must be initializable and openable.
1350
Unsupported formats may not support initialization or committing or
1351
some other features depending on the reason for not being supported.
1355
def check_conversion_target(self, target_format):
1356
raise NotImplementedError(self.check_conversion_target)
1358
def open(self, a_bzrdir, _found=False):
1359
"""Return an instance of this format for the bzrdir a_bzrdir.
1361
_found is a private parameter, do not use it.
1363
raise NotImplementedError(self.open)
1366
class PreSplitOutRepositoryFormat(RepositoryFormat):
1367
"""Base class for the pre split out repository formats."""
1369
rich_root_data = False
1371
def initialize(self, a_bzrdir, shared=False, _internal=False):
1372
"""Create a weave repository.
1374
TODO: when creating split out bzr branch formats, move this to a common
1375
base for Format5, Format6. or something like that.
1378
raise errors.IncompatibleFormat(self, a_bzrdir._format)
1381
# always initialized when the bzrdir is.
1382
return self.open(a_bzrdir, _found=True)
1384
# Create an empty weave
1386
weavefile.write_weave_v5(weave.Weave(), sio)
1387
empty_weave = sio.getvalue()
1389
mutter('creating repository in %s.', a_bzrdir.transport.base)
1390
dirs = ['revision-store', 'weaves']
1391
files = [('inventory.weave', StringIO(empty_weave)),
1394
# FIXME: RBC 20060125 don't peek under the covers
1395
# NB: no need to escape relative paths that are url safe.
1396
control_files = lockable_files.LockableFiles(a_bzrdir.transport,
1397
'branch-lock', lockable_files.TransportLock)
1398
control_files.create_lock()
1399
control_files.lock_write()
1400
control_files._transport.mkdir_multi(dirs,
1401
mode=control_files._dir_mode)
1403
for file, content in files:
1404
control_files.put(file, content)
1406
control_files.unlock()
1407
return self.open(a_bzrdir, _found=True)
1409
def _get_control_store(self, repo_transport, control_files):
1410
"""Return the control store for this repository."""
1411
return self._get_versioned_file_store('',
1416
def _get_text_store(self, transport, control_files):
1417
"""Get a store for file texts for this format."""
1418
raise NotImplementedError(self._get_text_store)
1420
def open(self, a_bzrdir, _found=False):
1421
"""See RepositoryFormat.open()."""
1423
# we are being called directly and must probe.
1424
raise NotImplementedError
1426
repo_transport = a_bzrdir.get_repository_transport(None)
1427
control_files = a_bzrdir._control_files
1428
text_store = self._get_text_store(repo_transport, control_files)
1429
control_store = self._get_control_store(repo_transport, control_files)
1430
_revision_store = self._get_revision_store(repo_transport, control_files)
1431
return AllInOneRepository(_format=self,
1433
_revision_store=_revision_store,
1434
control_store=control_store,
1435
text_store=text_store)
1437
def check_conversion_target(self, target_format):
1441
class RepositoryFormat4(PreSplitOutRepositoryFormat):
1442
"""Bzr repository format 4.
1444
This repository format has:
1446
- TextStores for texts, inventories,revisions.
1448
This format is deprecated: it indexes texts using a text id which is
1449
removed in format 5; initialization and write support for this format
1454
super(RepositoryFormat4, self).__init__()
1455
self._matchingbzrdir = bzrdir.BzrDirFormat4()
1457
def get_format_description(self):
1458
"""See RepositoryFormat.get_format_description()."""
1459
return "Repository format 4"
1461
def initialize(self, url, shared=False, _internal=False):
1462
"""Format 4 branches cannot be created."""
1463
raise errors.UninitializableFormat(self)
1465
def is_supported(self):
1466
"""Format 4 is not supported.
1468
It is not supported because the model changed from 4 to 5 and the
1469
conversion logic is expensive - so doing it on the fly was not
1474
def _get_control_store(self, repo_transport, control_files):
1475
"""Format 4 repositories have no formal control store at this point.
1477
This will cause any control-file-needing apis to fail - this is desired.
1481
def _get_revision_store(self, repo_transport, control_files):
1482
"""See RepositoryFormat._get_revision_store()."""
1483
from bzrlib.xml4 import serializer_v4
1484
return self._get_text_rev_store(repo_transport,
1487
serializer=serializer_v4)
1489
def _get_text_store(self, transport, control_files):
1490
"""See RepositoryFormat._get_text_store()."""
1493
class RepositoryFormat5(PreSplitOutRepositoryFormat):
1494
"""Bzr control format 5.
1496
This repository format has:
1497
- weaves for file texts and inventory
1499
- TextStores for revisions and signatures.
1503
super(RepositoryFormat5, self).__init__()
1504
self._matchingbzrdir = bzrdir.BzrDirFormat5()
1506
def get_format_description(self):
1507
"""See RepositoryFormat.get_format_description()."""
1508
return "Weave repository format 5"
1510
def _get_revision_store(self, repo_transport, control_files):
1511
"""See RepositoryFormat._get_revision_store()."""
1512
"""Return the revision store object for this a_bzrdir."""
1513
return self._get_text_rev_store(repo_transport,
1518
def _get_text_store(self, transport, control_files):
1519
"""See RepositoryFormat._get_text_store()."""
1520
return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
1523
class RepositoryFormat6(PreSplitOutRepositoryFormat):
1524
"""Bzr control format 6.
1526
This repository format has:
1527
- weaves for file texts and inventory
1528
- hash subdirectory based stores.
1529
- TextStores for revisions and signatures.
1533
super(RepositoryFormat6, self).__init__()
1534
self._matchingbzrdir = bzrdir.BzrDirFormat6()
1536
def get_format_description(self):
1537
"""See RepositoryFormat.get_format_description()."""
1538
return "Weave repository format 6"
1540
def _get_revision_store(self, repo_transport, control_files):
1541
"""See RepositoryFormat._get_revision_store()."""
1542
return self._get_text_rev_store(repo_transport,
1548
def _get_text_store(self, transport, control_files):
1549
"""See RepositoryFormat._get_text_store()."""
1550
return self._get_versioned_file_store('weaves', transport, control_files)
1553
class MetaDirRepositoryFormat(RepositoryFormat):
1554
"""Common base class for the new repositories using the metadir layout."""
1556
rich_root_data = False
1559
super(MetaDirRepositoryFormat, self).__init__()
1560
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1562
def _create_control_files(self, a_bzrdir):
1563
"""Create the required files and the initial control_files object."""
1564
# FIXME: RBC 20060125 don't peek under the covers
1565
# NB: no need to escape relative paths that are url safe.
1566
repository_transport = a_bzrdir.get_repository_transport(self)
1567
control_files = lockable_files.LockableFiles(repository_transport,
1568
'lock', lockdir.LockDir)
1569
control_files.create_lock()
1570
return control_files
1572
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1573
"""Upload the initial blank content."""
1574
control_files = self._create_control_files(a_bzrdir)
1575
control_files.lock_write()
1577
control_files._transport.mkdir_multi(dirs,
1578
mode=control_files._dir_mode)
1579
for file, content in files:
1580
control_files.put(file, content)
1581
for file, content in utf8_files:
1582
control_files.put_utf8(file, content)
1584
control_files.put_utf8('shared-storage', '')
1586
control_files.unlock()
1589
class RepositoryFormat7(MetaDirRepositoryFormat):
1590
"""Bzr repository 7.
1592
This repository format has:
1593
- weaves for file texts and inventory
1594
- hash subdirectory based stores.
1595
- TextStores for revisions and signatures.
1596
- a format marker of its own
1597
- an optional 'shared-storage' flag
1598
- an optional 'no-working-trees' flag
1601
def _get_control_store(self, repo_transport, control_files):
1602
"""Return the control store for this repository."""
1603
return self._get_versioned_file_store('',
1608
def get_format_string(self):
1609
"""See RepositoryFormat.get_format_string()."""
1610
return "Bazaar-NG Repository format 7"
1612
def get_format_description(self):
1613
"""See RepositoryFormat.get_format_description()."""
1614
return "Weave repository format 7"
1616
def check_conversion_target(self, target_format):
1619
def _get_revision_store(self, repo_transport, control_files):
1620
"""See RepositoryFormat._get_revision_store()."""
1621
return self._get_text_rev_store(repo_transport,
1628
def _get_text_store(self, transport, control_files):
1629
"""See RepositoryFormat._get_text_store()."""
1630
return self._get_versioned_file_store('weaves',
1634
def initialize(self, a_bzrdir, shared=False):
1635
"""Create a weave repository.
1637
:param shared: If true the repository will be initialized as a shared
1640
# Create an empty weave
1642
weavefile.write_weave_v5(weave.Weave(), sio)
1643
empty_weave = sio.getvalue()
1645
mutter('creating repository in %s.', a_bzrdir.transport.base)
1646
dirs = ['revision-store', 'weaves']
1647
files = [('inventory.weave', StringIO(empty_weave)),
1649
utf8_files = [('format', self.get_format_string())]
1651
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1652
return self.open(a_bzrdir=a_bzrdir, _found=True)
1654
def open(self, a_bzrdir, _found=False, _override_transport=None):
1655
"""See RepositoryFormat.open().
1657
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1658
repository at a slightly different url
1659
than normal. I.e. during 'upgrade'.
1662
format = RepositoryFormat.find_format(a_bzrdir)
1663
assert format.__class__ == self.__class__
1664
if _override_transport is not None:
1665
repo_transport = _override_transport
1667
repo_transport = a_bzrdir.get_repository_transport(None)
1668
control_files = lockable_files.LockableFiles(repo_transport,
1669
'lock', lockdir.LockDir)
1670
text_store = self._get_text_store(repo_transport, control_files)
1671
control_store = self._get_control_store(repo_transport, control_files)
1672
_revision_store = self._get_revision_store(repo_transport, control_files)
1673
return WeaveMetaDirRepository(_format=self,
1675
control_files=control_files,
1676
_revision_store=_revision_store,
1677
control_store=control_store,
1678
text_store=text_store)
1681
class RepositoryFormatKnit(MetaDirRepositoryFormat):
1682
"""Bzr repository knit format (generalized).
1684
This repository format has:
1685
- knits for file texts and inventory
1686
- hash subdirectory based stores.
1687
- knits for revisions and signatures
1688
- TextStores for revisions and signatures.
1689
- a format marker of its own
1690
- an optional 'shared-storage' flag
1691
- an optional 'no-working-trees' flag
1695
def _get_control_store(self, repo_transport, control_files):
1696
"""Return the control store for this repository."""
1697
return VersionedFileStore(
1700
file_mode=control_files._file_mode,
1701
versionedfile_class=knit.KnitVersionedFile,
1702
versionedfile_kwargs={'factory':knit.KnitPlainFactory()},
1705
def _get_revision_store(self, repo_transport, control_files):
1706
"""See RepositoryFormat._get_revision_store()."""
1707
from bzrlib.store.revision.knit import KnitRevisionStore
1708
versioned_file_store = VersionedFileStore(
1710
file_mode=control_files._file_mode,
1713
versionedfile_class=knit.KnitVersionedFile,
1714
versionedfile_kwargs={'delta':False,
1715
'factory':knit.KnitPlainFactory(),
1719
return KnitRevisionStore(versioned_file_store)
1721
def _get_text_store(self, transport, control_files):
1722
"""See RepositoryFormat._get_text_store()."""
1723
return self._get_versioned_file_store('knits',
1726
versionedfile_class=knit.KnitVersionedFile,
1727
versionedfile_kwargs={
1728
'create_parent_dir':True,
1729
'delay_create':True,
1730
'dir_mode':control_files._dir_mode,
1734
def initialize(self, a_bzrdir, shared=False):
1735
"""Create a knit format 1 repository.
1737
:param a_bzrdir: bzrdir to contain the new repository; must already
1739
:param shared: If true the repository will be initialized as a shared
1742
mutter('creating repository in %s.', a_bzrdir.transport.base)
1743
dirs = ['revision-store', 'knits']
1745
utf8_files = [('format', self.get_format_string())]
1747
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1748
repo_transport = a_bzrdir.get_repository_transport(None)
1749
control_files = lockable_files.LockableFiles(repo_transport,
1750
'lock', lockdir.LockDir)
1751
control_store = self._get_control_store(repo_transport, control_files)
1752
transaction = transactions.WriteTransaction()
1753
# trigger a write of the inventory store.
1754
control_store.get_weave_or_empty('inventory', transaction)
1755
_revision_store = self._get_revision_store(repo_transport, control_files)
1756
# the revision id here is irrelevant: it will not be stored, and cannot
1758
_revision_store.has_revision_id('A', transaction)
1759
_revision_store.get_signature_file(transaction)
1760
return self.open(a_bzrdir=a_bzrdir, _found=True)
1762
def open(self, a_bzrdir, _found=False, _override_transport=None):
1763
"""See RepositoryFormat.open().
1765
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1766
repository at a slightly different url
1767
than normal. I.e. during 'upgrade'.
1770
format = RepositoryFormat.find_format(a_bzrdir)
1771
assert format.__class__ == self.__class__
1772
if _override_transport is not None:
1773
repo_transport = _override_transport
1775
repo_transport = a_bzrdir.get_repository_transport(None)
1776
control_files = lockable_files.LockableFiles(repo_transport,
1777
'lock', lockdir.LockDir)
1778
text_store = self._get_text_store(repo_transport, control_files)
1779
control_store = self._get_control_store(repo_transport, control_files)
1780
_revision_store = self._get_revision_store(repo_transport, control_files)
1781
return KnitRepository(_format=self,
1783
control_files=control_files,
1784
_revision_store=_revision_store,
1785
control_store=control_store,
1786
text_store=text_store)
1789
class RepositoryFormatKnit1(RepositoryFormatKnit):
1790
"""Bzr repository knit format 1.
1792
This repository format has:
1793
- knits for file texts and inventory
1794
- hash subdirectory based stores.
1795
- knits for revisions and signatures
1796
- TextStores for revisions and signatures.
1797
- a format marker of its own
1798
- an optional 'shared-storage' flag
1799
- an optional 'no-working-trees' flag
1802
This format was introduced in bzr 0.8.
1804
def get_format_string(self):
1805
"""See RepositoryFormat.get_format_string()."""
1806
return "Bazaar-NG Knit Repository Format 1"
1808
def get_format_description(self):
1809
"""See RepositoryFormat.get_format_description()."""
1810
return "Knit repository format 1"
1812
def check_conversion_target(self, target_format):
1816
class RepositoryFormatKnit2(RepositoryFormatKnit):
1817
"""Bzr repository knit format 2.
1819
THIS FORMAT IS EXPERIMENTAL
1820
This repository format has:
1821
- knits for file texts and inventory
1822
- hash subdirectory based stores.
1823
- knits for revisions and signatures
1824
- TextStores for revisions and signatures.
1825
- a format marker of its own
1826
- an optional 'shared-storage' flag
1827
- an optional 'no-working-trees' flag
1829
- Support for recording full info about the tree root
1833
rich_root_data = True
1835
def get_format_string(self):
1836
"""See RepositoryFormat.get_format_string()."""
1837
return "Bazaar Knit Repository Format 2\n"
1839
def get_format_description(self):
1840
"""See RepositoryFormat.get_format_description()."""
1841
return "Knit repository format 2"
1843
def check_conversion_target(self, target_format):
1844
if not target_format.rich_root_data:
1845
raise errors.BadConversionTarget(
1846
'Does not support rich root data.', target_format)
1848
def open(self, a_bzrdir, _found=False, _override_transport=None):
1849
"""See RepositoryFormat.open().
1851
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1852
repository at a slightly different url
1853
than normal. I.e. during 'upgrade'.
1856
format = RepositoryFormat.find_format(a_bzrdir)
1857
assert format.__class__ == self.__class__
1858
if _override_transport is not None:
1859
repo_transport = _override_transport
1861
repo_transport = a_bzrdir.get_repository_transport(None)
1862
control_files = lockable_files.LockableFiles(repo_transport, 'lock',
1864
text_store = self._get_text_store(repo_transport, control_files)
1865
control_store = self._get_control_store(repo_transport, control_files)
1866
_revision_store = self._get_revision_store(repo_transport, control_files)
1867
return KnitRepository2(_format=self,
1869
control_files=control_files,
1870
_revision_store=_revision_store,
1871
control_store=control_store,
1872
text_store=text_store)
1876
# formats which have no format string are not discoverable
1877
# and not independently creatable, so are not registered.
1878
RepositoryFormat.register_format(RepositoryFormat7())
1879
# KEEP in sync with bzrdir.format_registry default, which controls the overall
1880
# default control directory format
1881
_default_format = RepositoryFormatKnit1()
1882
RepositoryFormat.register_format(_default_format)
1883
RepositoryFormat.register_format(RepositoryFormatKnit2())
1884
RepositoryFormat._set_default_format(_default_format)
1885
_legacy_formats = [RepositoryFormat4(),
1886
RepositoryFormat5(),
1887
RepositoryFormat6()]
1890
class InterRepository(InterObject):
1891
"""This class represents operations taking place between two repositories.
1893
Its instances have methods like copy_content and fetch, and contain
1894
references to the source and target repositories these operations can be
1897
Often we will provide convenience methods on 'repository' which carry out
1898
operations with another repository - they will always forward to
1899
InterRepository.get(other).method_name(parameters).
1903
"""The available optimised InterRepository types."""
1905
def copy_content(self, revision_id=None, basis=None):
1906
raise NotImplementedError(self.copy_content)
1908
def fetch(self, revision_id=None, pb=None):
1909
"""Fetch the content required to construct revision_id.
1911
The content is copied from self.source to self.target.
1913
:param revision_id: if None all content is copied, if NULL_REVISION no
1915
:param pb: optional progress bar to use for progress reports. If not
1916
provided a default one will be created.
1918
Returns the copied revision count and the failed revisions in a tuple:
1921
raise NotImplementedError(self.fetch)
1924
def missing_revision_ids(self, revision_id=None):
1925
"""Return the revision ids that source has that target does not.
1927
These are returned in topological order.
1929
:param revision_id: only return revision ids included by this
1932
# generic, possibly worst case, slow code path.
1933
target_ids = set(self.target.all_revision_ids())
1934
if revision_id is not None:
1935
# TODO: jam 20070210 InterRepository is internal enough that it
1936
# should assume revision_ids are already utf-8
1937
revision_id = osutils.safe_revision_id(revision_id)
1938
source_ids = self.source.get_ancestry(revision_id)
1939
assert source_ids[0] is None
1942
source_ids = self.source.all_revision_ids()
1943
result_set = set(source_ids).difference(target_ids)
1944
# this may look like a no-op: its not. It preserves the ordering
1945
# other_ids had while only returning the members from other_ids
1946
# that we've decided we need.
1947
return [rev_id for rev_id in source_ids if rev_id in result_set]
1950
class InterSameDataRepository(InterRepository):
1951
"""Code for converting between repositories that represent the same data.
1953
Data format and model must match for this to work.
1956
_matching_repo_format = RepositoryFormat4()
1957
"""Repository format for testing with."""
1960
def is_compatible(source, target):
1961
if not isinstance(source, Repository):
1963
if not isinstance(target, Repository):
1965
if source._format.rich_root_data == target._format.rich_root_data:
1971
def copy_content(self, revision_id=None, basis=None):
1972
"""Make a complete copy of the content in self into destination.
1974
This is a destructive operation! Do not use it on existing
1977
:param revision_id: Only copy the content needed to construct
1978
revision_id and its parents.
1979
:param basis: Copy the needed data preferentially from basis.
1982
self.target.set_make_working_trees(self.source.make_working_trees())
1983
except NotImplementedError:
1985
# TODO: jam 20070210 This is fairly internal, so we should probably
1986
# just assert that revision_id is not unicode.
1987
revision_id = osutils.safe_revision_id(revision_id)
1988
# grab the basis available data
1989
if basis is not None:
1990
self.target.fetch(basis, revision_id=revision_id)
1991
# but don't bother fetching if we have the needed data now.
1992
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1993
self.target.has_revision(revision_id)):
1995
self.target.fetch(self.source, revision_id=revision_id)
1998
def fetch(self, revision_id=None, pb=None):
1999
"""See InterRepository.fetch()."""
2000
from bzrlib.fetch import GenericRepoFetcher
2001
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2002
self.source, self.source._format, self.target,
2003
self.target._format)
2004
# TODO: jam 20070210 This should be an assert, not a translate
2005
revision_id = osutils.safe_revision_id(revision_id)
2006
f = GenericRepoFetcher(to_repository=self.target,
2007
from_repository=self.source,
2008
last_revision=revision_id,
2010
return f.count_copied, f.failed_revisions
2013
class InterWeaveRepo(InterSameDataRepository):
2014
"""Optimised code paths between Weave based repositories."""
2016
_matching_repo_format = RepositoryFormat7()
2017
"""Repository format for testing with."""
2020
def is_compatible(source, target):
2021
"""Be compatible with known Weave formats.
2023
We don't test for the stores being of specific types because that
2024
could lead to confusing results, and there is no need to be
2028
return (isinstance(source._format, (RepositoryFormat5,
2030
RepositoryFormat7)) and
2031
isinstance(target._format, (RepositoryFormat5,
2033
RepositoryFormat7)))
2034
except AttributeError:
2038
def copy_content(self, revision_id=None, basis=None):
2039
"""See InterRepository.copy_content()."""
2040
# weave specific optimised path:
2041
# TODO: jam 20070210 Internal, should be an assert, not translate
2042
revision_id = osutils.safe_revision_id(revision_id)
2043
if basis is not None:
2044
# copy the basis in, then fetch remaining data.
2045
basis.copy_content_into(self.target, revision_id)
2046
# the basis copy_content_into could miss-set this.
2048
self.target.set_make_working_trees(self.source.make_working_trees())
2049
except NotImplementedError:
2051
self.target.fetch(self.source, revision_id=revision_id)
2054
self.target.set_make_working_trees(self.source.make_working_trees())
2055
except NotImplementedError:
2057
# FIXME do not peek!
2058
if self.source.control_files._transport.listable():
2059
pb = ui.ui_factory.nested_progress_bar()
2061
self.target.weave_store.copy_all_ids(
2062
self.source.weave_store,
2064
from_transaction=self.source.get_transaction(),
2065
to_transaction=self.target.get_transaction())
2066
pb.update('copying inventory', 0, 1)
2067
self.target.control_weaves.copy_multi(
2068
self.source.control_weaves, ['inventory'],
2069
from_transaction=self.source.get_transaction(),
2070
to_transaction=self.target.get_transaction())
2071
self.target._revision_store.text_store.copy_all_ids(
2072
self.source._revision_store.text_store,
2077
self.target.fetch(self.source, revision_id=revision_id)
2080
def fetch(self, revision_id=None, pb=None):
2081
"""See InterRepository.fetch()."""
2082
from bzrlib.fetch import GenericRepoFetcher
2083
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2084
self.source, self.source._format, self.target, self.target._format)
2085
# TODO: jam 20070210 This should be an assert, not a translate
2086
revision_id = osutils.safe_revision_id(revision_id)
2087
f = GenericRepoFetcher(to_repository=self.target,
2088
from_repository=self.source,
2089
last_revision=revision_id,
2091
return f.count_copied, f.failed_revisions
2094
def missing_revision_ids(self, revision_id=None):
2095
"""See InterRepository.missing_revision_ids()."""
2096
# we want all revisions to satisfy revision_id in source.
2097
# but we don't want to stat every file here and there.
2098
# we want then, all revisions other needs to satisfy revision_id
2099
# checked, but not those that we have locally.
2100
# so the first thing is to get a subset of the revisions to
2101
# satisfy revision_id in source, and then eliminate those that
2102
# we do already have.
2103
# this is slow on high latency connection to self, but as as this
2104
# disk format scales terribly for push anyway due to rewriting
2105
# inventory.weave, this is considered acceptable.
2107
if revision_id is not None:
2108
source_ids = self.source.get_ancestry(revision_id)
2109
assert source_ids[0] is None
2112
source_ids = self.source._all_possible_ids()
2113
source_ids_set = set(source_ids)
2114
# source_ids is the worst possible case we may need to pull.
2115
# now we want to filter source_ids against what we actually
2116
# have in target, but don't try to check for existence where we know
2117
# we do not have a revision as that would be pointless.
2118
target_ids = set(self.target._all_possible_ids())
2119
possibly_present_revisions = target_ids.intersection(source_ids_set)
2120
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
2121
required_revisions = source_ids_set.difference(actually_present_revisions)
2122
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
2123
if revision_id is not None:
2124
# we used get_ancestry to determine source_ids then we are assured all
2125
# revisions referenced are present as they are installed in topological order.
2126
# and the tip revision was validated by get_ancestry.
2127
return required_topo_revisions
2129
# if we just grabbed the possibly available ids, then
2130
# we only have an estimate of whats available and need to validate
2131
# that against the revision records.
2132
return self.source._eliminate_revisions_not_present(required_topo_revisions)
2135
class InterKnitRepo(InterSameDataRepository):
2136
"""Optimised code paths between Knit based repositories."""
2138
_matching_repo_format = RepositoryFormatKnit1()
2139
"""Repository format for testing with."""
2142
def is_compatible(source, target):
2143
"""Be compatible with known Knit formats.
2145
We don't test for the stores being of specific types because that
2146
could lead to confusing results, and there is no need to be
2150
return (isinstance(source._format, (RepositoryFormatKnit1)) and
2151
isinstance(target._format, (RepositoryFormatKnit1)))
2152
except AttributeError:
2156
def fetch(self, revision_id=None, pb=None):
2157
"""See InterRepository.fetch()."""
2158
from bzrlib.fetch import KnitRepoFetcher
2159
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2160
self.source, self.source._format, self.target, self.target._format)
2161
# TODO: jam 20070210 This should be an assert, not a translate
2162
revision_id = osutils.safe_revision_id(revision_id)
2163
f = KnitRepoFetcher(to_repository=self.target,
2164
from_repository=self.source,
2165
last_revision=revision_id,
2167
return f.count_copied, f.failed_revisions
2170
def missing_revision_ids(self, revision_id=None):
2171
"""See InterRepository.missing_revision_ids()."""
2172
if revision_id is not None:
2173
source_ids = self.source.get_ancestry(revision_id)
2174
assert source_ids[0] is None
2177
source_ids = self.source._all_possible_ids()
2178
source_ids_set = set(source_ids)
2179
# source_ids is the worst possible case we may need to pull.
2180
# now we want to filter source_ids against what we actually
2181
# have in target, but don't try to check for existence where we know
2182
# we do not have a revision as that would be pointless.
2183
target_ids = set(self.target._all_possible_ids())
2184
possibly_present_revisions = target_ids.intersection(source_ids_set)
2185
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
2186
required_revisions = source_ids_set.difference(actually_present_revisions)
2187
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
2188
if revision_id is not None:
2189
# we used get_ancestry to determine source_ids then we are assured all
2190
# revisions referenced are present as they are installed in topological order.
2191
# and the tip revision was validated by get_ancestry.
2192
return required_topo_revisions
2194
# if we just grabbed the possibly available ids, then
2195
# we only have an estimate of whats available and need to validate
2196
# that against the revision records.
2197
return self.source._eliminate_revisions_not_present(required_topo_revisions)
2200
class InterModel1and2(InterRepository):
2202
_matching_repo_format = None
2205
def is_compatible(source, target):
2206
if not isinstance(source, Repository):
2208
if not isinstance(target, Repository):
2210
if not source._format.rich_root_data and target._format.rich_root_data:
2216
def fetch(self, revision_id=None, pb=None):
2217
"""See InterRepository.fetch()."""
2218
from bzrlib.fetch import Model1toKnit2Fetcher
2219
# TODO: jam 20070210 This should be an assert, not a translate
2220
revision_id = osutils.safe_revision_id(revision_id)
2221
f = Model1toKnit2Fetcher(to_repository=self.target,
2222
from_repository=self.source,
2223
last_revision=revision_id,
2225
return f.count_copied, f.failed_revisions
2228
def copy_content(self, revision_id=None, basis=None):
2229
"""Make a complete copy of the content in self into destination.
2231
This is a destructive operation! Do not use it on existing
2234
:param revision_id: Only copy the content needed to construct
2235
revision_id and its parents.
2236
:param basis: Copy the needed data preferentially from basis.
2239
self.target.set_make_working_trees(self.source.make_working_trees())
2240
except NotImplementedError:
2242
# TODO: jam 20070210 Internal, assert, don't translate
2243
revision_id = osutils.safe_revision_id(revision_id)
2244
# grab the basis available data
2245
if basis is not None:
2246
self.target.fetch(basis, revision_id=revision_id)
2247
# but don't bother fetching if we have the needed data now.
2248
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
2249
self.target.has_revision(revision_id)):
2251
self.target.fetch(self.source, revision_id=revision_id)
2254
class InterKnit1and2(InterKnitRepo):
2256
_matching_repo_format = None
2259
def is_compatible(source, target):
2260
"""Be compatible with Knit1 source and Knit2 target"""
2262
return (isinstance(source._format, (RepositoryFormatKnit1)) and
2263
isinstance(target._format, (RepositoryFormatKnit2)))
2264
except AttributeError:
2268
def fetch(self, revision_id=None, pb=None):
2269
"""See InterRepository.fetch()."""
2270
from bzrlib.fetch import Knit1to2Fetcher
2271
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2272
self.source, self.source._format, self.target,
2273
self.target._format)
2274
# TODO: jam 20070210 This should be an assert, not a translate
2275
revision_id = osutils.safe_revision_id(revision_id)
2276
f = Knit1to2Fetcher(to_repository=self.target,
2277
from_repository=self.source,
2278
last_revision=revision_id,
2280
return f.count_copied, f.failed_revisions
2283
InterRepository.register_optimiser(InterSameDataRepository)
2284
InterRepository.register_optimiser(InterWeaveRepo)
2285
InterRepository.register_optimiser(InterKnitRepo)
2286
InterRepository.register_optimiser(InterModel1and2)
2287
InterRepository.register_optimiser(InterKnit1and2)
2290
class RepositoryTestProviderAdapter(object):
2291
"""A tool to generate a suite testing multiple repository formats at once.
2293
This is done by copying the test once for each transport and injecting
2294
the transport_server, transport_readonly_server, and bzrdir_format and
2295
repository_format classes into each copy. Each copy is also given a new id()
2296
to make it easy to identify.
2299
def __init__(self, transport_server, transport_readonly_server, formats):
2300
self._transport_server = transport_server
2301
self._transport_readonly_server = transport_readonly_server
2302
self._formats = formats
2304
def adapt(self, test):
2305
result = unittest.TestSuite()
2306
for repository_format, bzrdir_format in self._formats:
2307
new_test = deepcopy(test)
2308
new_test.transport_server = self._transport_server
2309
new_test.transport_readonly_server = self._transport_readonly_server
2310
new_test.bzrdir_format = bzrdir_format
2311
new_test.repository_format = repository_format
2312
def make_new_test_id():
2313
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
2314
return lambda: new_id
2315
new_test.id = make_new_test_id()
2316
result.addTest(new_test)
2320
class InterRepositoryTestProviderAdapter(object):
2321
"""A tool to generate a suite testing multiple inter repository formats.
2323
This is done by copying the test once for each interrepo provider and injecting
2324
the transport_server, transport_readonly_server, repository_format and
2325
repository_to_format classes into each copy.
2326
Each copy is also given a new id() to make it easy to identify.
2329
def __init__(self, transport_server, transport_readonly_server, formats):
2330
self._transport_server = transport_server
2331
self._transport_readonly_server = transport_readonly_server
2332
self._formats = formats
2334
def adapt(self, test):
2335
result = unittest.TestSuite()
2336
for interrepo_class, repository_format, repository_format_to in self._formats:
2337
new_test = deepcopy(test)
2338
new_test.transport_server = self._transport_server
2339
new_test.transport_readonly_server = self._transport_readonly_server
2340
new_test.interrepo_class = interrepo_class
2341
new_test.repository_format = repository_format
2342
new_test.repository_format_to = repository_format_to
2343
def make_new_test_id():
2344
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
2345
return lambda: new_id
2346
new_test.id = make_new_test_id()
2347
result.addTest(new_test)
2351
def default_test_list():
2352
"""Generate the default list of interrepo permutations to test."""
2354
# test the default InterRepository between format 6 and the current
2356
# XXX: robertc 20060220 reinstate this when there are two supported
2357
# formats which do not have an optimal code path between them.
2358
#result.append((InterRepository,
2359
# RepositoryFormat6(),
2360
# RepositoryFormatKnit1()))
2361
for optimiser in InterRepository._optimisers:
2362
if optimiser._matching_repo_format is not None:
2363
result.append((optimiser,
2364
optimiser._matching_repo_format,
2365
optimiser._matching_repo_format
2367
# if there are specific combinations we want to use, we can add them
2369
result.append((InterModel1and2, RepositoryFormat5(),
2370
RepositoryFormatKnit2()))
2371
result.append((InterKnit1and2, RepositoryFormatKnit1(),
2372
RepositoryFormatKnit2()))
2376
class CopyConverter(object):
2377
"""A repository conversion tool which just performs a copy of the content.
2379
This is slow but quite reliable.
2382
def __init__(self, target_format):
2383
"""Create a CopyConverter.
2385
:param target_format: The format the resulting repository should be.
2387
self.target_format = target_format
2389
def convert(self, repo, pb):
2390
"""Perform the conversion of to_convert, giving feedback via pb.
2392
:param to_convert: The disk object to convert.
2393
:param pb: a progress bar to use for progress information.
2398
# this is only useful with metadir layouts - separated repo content.
2399
# trigger an assertion if not such
2400
repo._format.get_format_string()
2401
self.repo_dir = repo.bzrdir
2402
self.step('Moving repository to repository.backup')
2403
self.repo_dir.transport.move('repository', 'repository.backup')
2404
backup_transport = self.repo_dir.transport.clone('repository.backup')
2405
repo._format.check_conversion_target(self.target_format)
2406
self.source_repo = repo._format.open(self.repo_dir,
2408
_override_transport=backup_transport)
2409
self.step('Creating new repository')
2410
converted = self.target_format.initialize(self.repo_dir,
2411
self.source_repo.is_shared())
2412
converted.lock_write()
2414
self.step('Copying content into repository.')
2415
self.source_repo.copy_content_into(converted)
2418
self.step('Deleting old repository content.')
2419
self.repo_dir.transport.delete_tree('repository.backup')
2420
self.pb.note('repository converted')
2422
def step(self, message):
2423
"""Update the pb by a step."""
2425
self.pb.update(message, self.count, self.total)
2428
class CommitBuilder(object):
2429
"""Provides an interface to build up a commit.
2431
This allows describing a tree to be committed without needing to
2432
know the internals of the format of the repository.
2435
record_root_entry = False
2436
def __init__(self, repository, parents, config, timestamp=None,
2437
timezone=None, committer=None, revprops=None,
2439
"""Initiate a CommitBuilder.
2441
:param repository: Repository to commit to.
2442
:param parents: Revision ids of the parents of the new revision.
2443
:param config: Configuration to use.
2444
:param timestamp: Optional timestamp recorded for commit.
2445
:param timezone: Optional timezone for timestamp.
2446
:param committer: Optional committer to set for commit.
2447
:param revprops: Optional dictionary of revision properties.
2448
:param revision_id: Optional revision id.
2450
self._config = config
2452
if committer is None:
2453
self._committer = self._config.username()
2455
assert isinstance(committer, basestring), type(committer)
2456
self._committer = committer
2458
self.new_inventory = Inventory(None)
2459
self._new_revision_id = osutils.safe_revision_id(revision_id)
2460
self.parents = parents
2461
self.repository = repository
2464
if revprops is not None:
2465
self._revprops.update(revprops)
2467
if timestamp is None:
2468
timestamp = time.time()
2469
# Restrict resolution to 1ms
2470
self._timestamp = round(timestamp, 3)
2472
if timezone is None:
2473
self._timezone = local_time_offset()
2475
self._timezone = int(timezone)
2477
self._generate_revision_if_needed()
2479
def commit(self, message):
2480
"""Make the actual commit.
2482
:return: The revision id of the recorded revision.
2484
rev = _mod_revision.Revision(
2485
timestamp=self._timestamp,
2486
timezone=self._timezone,
2487
committer=self._committer,
2489
inventory_sha1=self.inv_sha1,
2490
revision_id=self._new_revision_id,
2491
properties=self._revprops)
2492
rev.parent_ids = self.parents
2493
self.repository.add_revision(self._new_revision_id, rev,
2494
self.new_inventory, self._config)
2495
return self._new_revision_id
2497
def revision_tree(self):
2498
"""Return the tree that was just committed.
2500
After calling commit() this can be called to get a RevisionTree
2501
representing the newly committed tree. This is preferred to
2502
calling Repository.revision_tree() because that may require
2503
deserializing the inventory, while we already have a copy in
2506
return RevisionTree(self.repository, self.new_inventory,
2507
self._new_revision_id)
2509
def finish_inventory(self):
2510
"""Tell the builder that the inventory is finished."""
2511
if self.new_inventory.root is None:
2512
symbol_versioning.warn('Root entry should be supplied to'
2513
' record_entry_contents, as of bzr 0.10.',
2514
DeprecationWarning, stacklevel=2)
2515
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
2516
self.new_inventory.revision_id = self._new_revision_id
2517
self.inv_sha1 = self.repository.add_inventory(
2518
self._new_revision_id,
2523
def _gen_revision_id(self):
2524
"""Return new revision-id."""
2525
return generate_ids.gen_revision_id(self._config.username(),
2528
def _generate_revision_if_needed(self):
2529
"""Create a revision id if None was supplied.
2531
If the repository can not support user-specified revision ids
2532
they should override this function and raise CannotSetRevisionId
2533
if _new_revision_id is not None.
2535
:raises: CannotSetRevisionId
2537
if self._new_revision_id is None:
2538
self._new_revision_id = self._gen_revision_id()
2540
def record_entry_contents(self, ie, parent_invs, path, tree):
2541
"""Record the content of ie from tree into the commit if needed.
2543
Side effect: sets ie.revision when unchanged
2545
:param ie: An inventory entry present in the commit.
2546
:param parent_invs: The inventories of the parent revisions of the
2548
:param path: The path the entry is at in the tree.
2549
:param tree: The tree which contains this entry and should be used to
2552
if self.new_inventory.root is None and ie.parent_id is not None:
2553
symbol_versioning.warn('Root entry should be supplied to'
2554
' record_entry_contents, as of bzr 0.10.',
2555
DeprecationWarning, stacklevel=2)
2556
self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
2558
self.new_inventory.add(ie)
2560
# ie.revision is always None if the InventoryEntry is considered
2561
# for committing. ie.snapshot will record the correct revision
2562
# which may be the sole parent if it is untouched.
2563
if ie.revision is not None:
2566
# In this revision format, root entries have no knit or weave
2567
if ie is self.new_inventory.root:
2568
# When serializing out to disk and back in
2569
# root.revision is always _new_revision_id
2570
ie.revision = self._new_revision_id
2572
previous_entries = ie.find_previous_heads(
2574
self.repository.weave_store,
2575
self.repository.get_transaction())
2576
# we are creating a new revision for ie in the history store
2578
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2580
def modified_directory(self, file_id, file_parents):
2581
"""Record the presence of a symbolic link.
2583
:param file_id: The file_id of the link to record.
2584
:param file_parents: The per-file parent revision ids.
2586
self._add_text_to_weave(file_id, [], file_parents.keys())
2588
def modified_file_text(self, file_id, file_parents,
2589
get_content_byte_lines, text_sha1=None,
2591
"""Record the text of file file_id
2593
:param file_id: The file_id of the file to record the text of.
2594
:param file_parents: The per-file parent revision ids.
2595
:param get_content_byte_lines: A callable which will return the byte
2597
:param text_sha1: Optional SHA1 of the file contents.
2598
:param text_size: Optional size of the file contents.
2600
# mutter('storing text of file {%s} in revision {%s} into %r',
2601
# file_id, self._new_revision_id, self.repository.weave_store)
2602
# special case to avoid diffing on renames or
2604
if (len(file_parents) == 1
2605
and text_sha1 == file_parents.values()[0].text_sha1
2606
and text_size == file_parents.values()[0].text_size):
2607
previous_ie = file_parents.values()[0]
2608
versionedfile = self.repository.weave_store.get_weave(file_id,
2609
self.repository.get_transaction())
2610
versionedfile.clone_text(self._new_revision_id,
2611
previous_ie.revision, file_parents.keys())
2612
return text_sha1, text_size
2614
new_lines = get_content_byte_lines()
2615
# TODO: Rather than invoking sha_strings here, _add_text_to_weave
2616
# should return the SHA1 and size
2617
self._add_text_to_weave(file_id, new_lines, file_parents.keys())
2618
return osutils.sha_strings(new_lines), \
2619
sum(map(len, new_lines))
2621
def modified_link(self, file_id, file_parents, link_target):
2622
"""Record the presence of a symbolic link.
2624
:param file_id: The file_id of the link to record.
2625
:param file_parents: The per-file parent revision ids.
2626
:param link_target: Target location of this link.
2628
self._add_text_to_weave(file_id, [], file_parents.keys())
2630
def _add_text_to_weave(self, file_id, new_lines, parents):
2631
versionedfile = self.repository.weave_store.get_weave_or_empty(
2632
file_id, self.repository.get_transaction())
2633
versionedfile.add_lines(self._new_revision_id, parents, new_lines)
2634
versionedfile.clear_cache()
2637
class _CommitBuilder(CommitBuilder):
2638
"""Temporary class so old CommitBuilders are detected properly
2640
Note: CommitBuilder works whether or not root entry is recorded.
2643
record_root_entry = True
2646
class RootCommitBuilder(CommitBuilder):
2647
"""This commitbuilder actually records the root id"""
2649
record_root_entry = True
2651
def record_entry_contents(self, ie, parent_invs, path, tree):
2652
"""Record the content of ie from tree into the commit if needed.
2654
Side effect: sets ie.revision when unchanged
2656
:param ie: An inventory entry present in the commit.
2657
:param parent_invs: The inventories of the parent revisions of the
2659
:param path: The path the entry is at in the tree.
2660
:param tree: The tree which contains this entry and should be used to
2663
assert self.new_inventory.root is not None or ie.parent_id is None
2664
self.new_inventory.add(ie)
2666
# ie.revision is always None if the InventoryEntry is considered
2667
# for committing. ie.snapshot will record the correct revision
2668
# which may be the sole parent if it is untouched.
2669
if ie.revision is not None:
2672
previous_entries = ie.find_previous_heads(
2674
self.repository.weave_store,
2675
self.repository.get_transaction())
2676
# we are creating a new revision for ie in the history store
2678
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2690
def _unescaper(match, _map=_unescape_map):
2691
return _map[match.group(1)]
2697
def _unescape_xml(data):
2698
"""Unescape predefined XML entities in a string of data."""
2700
if _unescape_re is None:
2701
_unescape_re = re.compile('\&([^;]*);')
2702
return _unescape_re.sub(_unescaper, data)